这里是情况:
我的模型如下:
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,)
然后我使用兴趣构建一个ModelForm:
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>
我希望在不检查任何一个表单字段并提交时看到“无”。
我希望在检查任何或所有表单字段并提交表单时看到“ Not None”。
但是,我看不到预期的事情。
答案 0 :(得分:1)
我对此改变了看法,并且有效:
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)