【发布时间】:2016-04-20 12:48:23
【问题描述】:
注意:Django/Python 初学者,希望这个问题清楚。
我正在创建一个表单,可以在一个表单中一次编辑模型(来宾)的多个实例,并同时提交。
此 Guest 模型链接到父模型 Invite,这意味着多个 Guest 附加到单个 Invite。
我已经设法为每个访客创建了一个表单集并显示它,但是当我提交它时,我收到以下错误。
NOT NULL constraint failed: app_guest.invite_id
我假设这是因为它没有将数据保存到的邀请,但我不知道把它要求的 invite_id 放在哪里。
到目前为止,这是我的观点:
def extra_view(request, code):
# Get the specific invite
invite = get_invite(code)
# Get guests attached to this invite
guests = invite.guest_set.all()
# Get the context from the request.
context = RequestContext(request)
# Store object of guests marked as attending
guests_attending = invite.guest_set.filter(attending=True, invite=invite)
form = ExtraForm(data=request.POST or None)
if form.is_valid():
# Save the new category to the database.
### FAILS HERE
form.save(commit=True)
# Go to Confirm page
HttpResponseRedirect('confirm')
else:
# The supplied form contained errors - just print them to the terminal for now
print form.errors
if guests_attending.count() > 1:
# If the request was not a POST, display the form to enter details.
guest_formset = modelformset_factory(Guest, form=ExtraForm, extra=0, max_num=guests_attending.count())
# Filter the formset so that only guests marked as attending are
filtered_guest_form = guest_formset(queryset=guests.filter(attending=True))
# Return the view
return render_to_response('weddingapp/extra.html', {'GuestForm': filtered_guest_form, 'invite': invite, 'guests_attending': guests_attending, 'form_errors': form.errors}, context)
else:
# Since there's no guests to create a form for, return Confirm view
return render(request, 'weddingapp/confirm.html', {
'invite': invite,
})
这是我的访客模型:
@python_2_unicode_compatible
class Guest(models.Model):
invite = models.ForeignKey(Invite, on_delete=models.CASCADE)
guest_name = models.CharField(max_length=200)
diet = models.CharField(max_length=250)
transport = models.NullBooleanField(default=False, null=True)
attending = models.NullBooleanField(null=True)
def __str__(self):
return self.guest_name
这是表格:
class ExtraForm(forms.ModelForm):
diet = forms.CharField(max_length=128, help_text="Please enter your diet restrictions", required=False)
transport = forms.BooleanField(initial=False, help_text="Will you be needing transport?", required=False)
# An inline class to provide additional information on the form.
class Meta:
# Provide an association between the ModelForm and a model
model = Guest
fields = ('diet', 'transport')
任何帮助将不胜感激。即使是关于构建所有这些的更好方法的建议也会有所帮助。谢谢。
【问题讨论】: