我有模型是這樣的:如何在Django中保存ManyToMany字段?
class GuestStatus(models.Model):
guest_status = models.CharField(max_length=200)
arrangement = models.IntegerField(unique=True, help_text="Start from 1. Guest status will be arranged alphabetically.")
class Guest(models.Model):
user = models.ForeignKey(User)
full_name = models.CharField(max_length=250)
status = models.ManyToManyField(GuestStatus, blank=True, null=True)
invitation_date = models.DateTimeField(blank=True, null=True)
我想ManyToManyField
被顯示爲複選框。這就是爲什麼我在做這樣的:
class GuestForm(ModelForm):
status = forms.ModelMultipleChoiceField(queryset=GuestStatus.objects.all().order_by('arrangement'), widget=forms.CheckboxSelectMultiple, required=False)
class Meta:
model = Guest
exclude = ['user', 'invitation_date']
我試圖保存表單是這樣的:
form = GuestForm(request.POST)
if form.is_valid():
status = form.cleaned_data['status']
guest.status = status
if status:
invitation_date = datetime.now()
else:
invitation_date = None
new_guest = form.save(commit=False)
new_guest.user = request.user
new_guest.save()
new_guest.status = status
form.save_m2m()
return HttpResponseRedirect('/list_guests/')
的形式保存所有的數據,但不能status
值。哪裏不對?另外,成功保存後,如何訪問模板中的狀態值?由於
因爲你'new_guest.status = status'您保存了'new_guest後' –
如果我在'new_guest.user = request.user'後面寫'new_guest.status = status',稍後再'new_guest.save()'我得到這個錯誤:'「需要有一個值在這個多對多關係可以使用前,可以使用字段「guest」 –
pynovice
如果表單具有'status'字段,則不需要將其顯式設置爲'new_guest.status =狀態',而不是'form.save_m2m()'。 – Rohan