首页 > 解决方案 > 当表单字段为 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”。

但是,我看不到我期望发生的事情。

标签: djangomany-to-manymodelformcleaned-datamodelmultiplechoicefield

解决方案


我改变了我的看法,它奏效了:

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)

推荐阅读