我正在尝试将用户详细信息与他创建的电话簿和联系人一起存储,以便我能够显示他们创建的电话簿和联系人。我不希望用户自己明确添加详细信息。它应该由后端处理。我可以成功地使用他创建的电话簿存储用户详细信息,但是当我尝试对联系人执行相同操作时,我收到属性错误。models.pyclass PhoneBook(models.Model): name = models.CharField(max_length=10, blank=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def __str__(self): return self.nameclass Contact(models.Model): first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) phone_number = models.CharField(max_length=13, blank=False, unique=True) phone_book = models.ManyToManyField(PhoneBook, related_name='phone_book') user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def __str__(self): return self.phone_numberviews.py@login_requireddef create_phone_book(request): form = CreatePhoneBookForm(request.POST or None) form.instance.user = request.user if form.is_valid(): form.save() form = CreatePhoneBookForm() context = {'form': form} return render(request, 'CallCenter/create_phone_book.html', context)@login_requireddef add_to_phone_book(request): form = AddToPhoneBookForm(request.POST or None) form.instance.user = request.user if form.is_valid(): form.save() form = AddToPhoneBookForm() context = {'form': form} return render(request, 'CallCenter/add_to_phone_book.html', context)forms.pyclass AddToPhoneBookForm(forms.Form): class Meta: model = Contact fields = ['first_name', 'last_name', 'phone_number', 'phone_book']class CreatePhoneBookForm(forms.Form): class Meta: model = PhoneBook fields = ['name']我得到的错误是 /call-center/add/ 的 AttributeError'AddToPhoneBookForm' 对象没有属性 'instance'
1 回答
慕婉清6462132
TA贡献1804条经验 获得超2个赞
您应该使用 a ModelForm,而不是 a Form。AForm本身没有实例,因此您可以定义:
class AddToPhoneBookForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['first_name', 'last_name', 'phone_number', 'phone_book']
class CreatePhoneBookForm(forms.ModelForm):
class Meta:
model = PhoneBook
fields = ['name']
通常当你发出一个成功的 post 请求时,你应该重定向,以实现Post/Redirect/Get模式 [wiki]。
添加回答
举报
0/150
提交
取消