情况如下:
我有一个模型如下:
class School(Model):
name = CharField(...)
许可模型有三个对象:
School.objects.create(name='school1') # id=1
School.objects.create(name='school2') # id=2
我还有另一个模型:
Interest(Model):
school_interest = ManyToManyField(School, blank=True,)
然后,我使用兴趣构建一个模型表单:
class InterestForm(ModelForm):
school_interest = ModelMultipleChoiceField(queryset=School.objects.all(), widget=CheckboxSelectMultiple, required=False)
class Meta:
model = Interest
fields = '__all__'
我有一个观点:
def interest(request):
template_name = 'interest_template.html'
context = {}
if request.POST:
interest_form = InterestForm(request.POST)
if interest_form.is_valid():
if interest_form.cleaned_data['school_interest'] is None:
return HttpResponse('None')
else:
return HttpResponse('Not None')
else:
interest_form = InterestForm()
context.update({interest_form': interest_form, })
return render(request, template_name, context)
在interest_template.html,我有:
<form method="post">
{% csrf_token %}
{{ interest_form.as_p }}
<button type="submit">Submit</button>
</form>
我希望在我不检查任何表单字段并提交时看到 None 。
我希望在检查任何或所有表单字段并提交表单时看到"并非没有"。
但是,我看不到我期望会发生什么。
我把我的观点改成了这个,它奏效了:
def interest(request):
template_name = 'interest_template.html'
context = {}
if request.POST:
interest_form = InterestForm(request.POST)
if interest_form.is_valid():
if not interest_form.cleaned_data['school_interest']:
return HttpResponse('None')
else:
return HttpResponse('Not None')
else:
interest_form = InterestForm()
context.update({interest_form': interest_form, })
return render(request, template_name, context)