0
因此,我有一個House模型的modelformset,它有一個manytomany字段的業主,由於我希望它自動保存當前登錄的用戶ID作爲所有者 - 我可能破解隱藏字段,但寧願知道如何正確完成。Django:模型FormSet上的完整性錯誤 - 不包括所需的M2M字段
爲清楚起見,完整性錯誤是owner_id不能爲空,我在通過硬編碼只是在manage_houses
views.py
def manage_houses(request):
HousesFormSet = modelformset_factory(House, form=ManageHousesForm)
if request.method == 'POST':
formset = HousesFormSet(request.POST)
# failed attempt at fixing integrity error
for form in formset:
form.owner_id = 1
if formset.is_valid():
if formset.save():
notice = "Success! Your houses were updated in the system."
notice_type = "success"
elif not formset.has_changed():
pass
else:
notice = "Something went wrong! Your houses may not have been updated."
notice_type = "error"
else:
formset = SpecialsFormSet()
response_details = { 'formset': formset,
'fields': ManageHousesForm.base_fields }
try:
response_details['notice'] = notice
response_details['notice_type'] = notice_type
except NameError:
pass
return render_to_response('houses/manage.djhtml', response_details)
的開始看到失敗修復它嘗試models.py
class House(models.Model):
class Meta:
app_label = 'houses'
# Fields
owners = models.ManyToManyField(User)
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=100, blank=True, editable=False, unique=True)
address = models.CharField(max_length=75)
def __unicode__(self):
return self.name
你能附上你的模型代碼嗎? –
編輯:附加。 –