所以我有一个 House 模型的 modelformset,它有一个 owner manytomany 字段,我排除了 owner 字段,因为我希望它自动将当前登录的用户 ID 保存为所有者 - 我可以破解这个带有隐藏字段,但宁愿知道它是如何正确完成的。
为清楚起见,完整性错误是 owner_id 不能为空,我尝试通过硬编码修复它只是为了在 manage_houses 的开头看到失败
视图.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)
模型.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