我在 django 中有一个表单集,它使用具有一对多关系的模型。许多与会者可以参加一个活动。
我正在表单集中发送模型的“许多”部分。问题是返回的数据没有设置主键。我收到验证错误,因为未设置表单集主键数据。
回到我的观点,我知道主键应该是什么。我想在验证之前设置它。在我发送表单以供显示之前设置值或设置值。但我不知道如何在表单集数据中设置它。
在下面的代码中,外键是event
.
选项1:在显示表单之前设置外键:
#models.py - note 2 foreign keys
class Attendee(models.Model):
event = models.ForeignKey(Event)
sponsor = models.ForeignKey(Customer)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
# forms.py
class AttendeeForm(forms.ModelForm):
event = forms.IntegerField(required=True, widget=forms.HiddenInput())
class Meta:
model = Attendee
fields = ( 'last_name', 'first_name', )
exclude = ('event', ) # excluded so user can't set foreign key
# views.py
event = get_object_or_404(Event, id=event_id)
AttendeeFormSet = inlineformset_factory(Event, Attendee, form=AttendeeForm, extra=1)
formset = AttendeeFormSet(instance=event, prefix='attendees')
# Error on form submit:
# Returns and redisplays the form along with message.
# (Hidden field event) The inline foreign key did not match the parent instance primary key.
# I also tried:
#AttendeeFormSet = inlineformset_factory(Event, Customer, Attendee, form=AttendeeForm, extra=1)
# which gave error:
# inlineformset_factory() got multiple values for keyword argument 'form'
选项 2:在返回 POST 上设置外键。请注意,即使存在数据,表单也无效,因为未设置外键。
formset = AttendeeFormSet(request.POST, request.FILES, prefix='attendees')
i=0
for form in formset.forms:
# How can I set the foreign key (event) field here?
pdb.set_trace()
if formset.is_valid():
attendees = formset.save_all()
(Pdb) p form.fields
{'last_name': <django.forms.fields.CharField object at 0xaa44a2c>,
'first_name': <django.forms.fields.CharField object at 0xaa449ec>,
'event': <django.forms.fields.IntegerField object at 0xaa44fec>}
(Pdb)
在我的表单集中解决我的外键问题的最佳方法是什么?如果选项 2 在测试之前如何设置此字段is_valid
?