所以我有一个用于House模型的modelformset,它拥有很多所有者字段,我排除了所有者字段,因为我希望它只是自动保存当前登录的用户ID作为所有者 - 我可能用隐藏的字段来破解它,但宁愿知道它是如何正确完成的。
为清楚起见,完整性错误是owner_id不能为null,我尝试通过硬编码修复它只是为了在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