我的模型中只有一个字段为null = True:
class TestModel(models.Model):
district = models.ForeignKey(District, on_delete=models.SET_NULL, null=True, default=None)
最简单的形式:
class DistrictForm(ModelForm):
class Meta:
model = TestModel
fields = ['district']
和我的view.py:
def district_details(request, district_id):
district = get_object_or_404(TestModel, pk=district_id)
context = {}
context['district'] = district
context['frmDistrict'] = DistrictForm(instance=district)
context['form_title'] = u'{} (id {})'.format(district, district.id)
return render(request, "editor/district_details.html", context)
def district_update(request, district_id):
district = get_object_or_404(TestModel, pk=district_id)
if (request.method == 'POST'):
form = DistrictForm(data=request.POST, instance=district)
if form.is_valid():
district.save()
messages.success(request, u'District «{}» successfully updated.'.format(district))
return redirect('editor:district_details', district_id=district.id)
else:
messages.warning(request, u"District is not updated. Please correct mistakes in the form." + unicode(form.is_bound))
else:
form = DistrictForm(instance=district)
return district_details(request, district_id=district_id)
和模板:
<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"></head><body>
{% for message in messages %}{{ message }}{% endfor %}
{{ form_title }}
<form id="frmSeries" action="{% url 'editor:district_update' district_id=district.id %}" method="POST">
{% csrf_token %}
{{ frmDistrict }}
<input type="submit" name="frmDistrict_submit" value="Сохранить" />
</form>
{% include 'results/panel_footer.html' %}
{{ frmDistrict.errors }}
{{ frmDistrict.non_field_errors }}
{{ request.POST }}
</body>
</html>
当我更改区域时它工作正常,但问题是当我在表单中选择空值时。 form_is_valid()为False,但frmDistrict.errors和frmDistrict.non_field_errors都为空!而form.is_bound()为True。
当我在表单中添加字段时,我遇到了另一个问题。以这种方式修改ModelForm之后:
class DistrictForm(ModelForm):
district = forms.ModelChoiceField(
queryset=District.objects.order_by('name'),
empty_label="empty",
required=False)
class Meta:
model = TestModel
fields = ['district']
当我选择&#34;空&#34;在下拉列表中,表单成功提交,但是&#34; district&#34;这个领域并没有改变!
有什么想法吗?提前谢谢!