幕布斯7119047
2022-06-28 10:10:27
我正在嘗試將用戶詳細(xì)信息與他創(chuàng)建的電話簿和聯(lián)系人一起存儲,以便我能夠顯示他們創(chuàng)建的電話簿和聯(lián)系人。我不希望用戶自己明確添加詳細(xì)信息。它應(yīng)該由后端處理。我可以成功地使用他創(chuàng)建的電話簿存儲用戶詳細(xì)信息,但是當(dāng)我嘗試對聯(lián)系人執(zhí)行相同操作時(shí),我收到屬性錯誤。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貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
您應(yīng)該使用 a ModelForm,而不是 a Form。AForm本身沒有實(shí)例,因此您可以定義:
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']
通常當(dāng)你發(fā)出一個(gè)成功的 post 請求時(shí),你應(yīng)該重定向,以實(shí)現(xiàn)Post/Redirect/Get模式 [wiki]。
添加回答
舉報(bào)
0/150
提交
取消