django - 当表单字段为 ModelMultipleChoiceField 时,如何在视图中接收 modelform_instance.cleaned_data['ManyToMany field']?
问题描述
情况如下:
我有一个模型如下:
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,)
然后我使用 Interest 构建一个 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>
当我没有检查任何一个表单字段并提交它时,我希望看到 None 。
当我检查任何或所有表单字段并提交表单时,我希望看到“Not 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)
推荐阅读
- java - 计算链表Java中的重复数
- sas - 如何在 SAS 中为宏构建循环?
- xml - 我想选择一些文本以 xml 输出
- autodesk-forge - 查询 BIM 360 项目属性时出错
- python - Python argparse:如何设置“--version”“--help”冲突?
- javascript - 如何在 CronJob 函数中停止 CronJob 函数?
- javascript - Angular 无法绑定到变量
- sql - 获取用户表中每个用户的活跃和总预订量(来自 1 个表)
- javascript - html javascript文本不会替换
- cakephp - Cakephp,在调试时不进入控制器