当表单字段为ModelMultipleChoiceField时,如何在视图中接收modelform_instance.cleaned_data ['ManyToMany field']? [英] how to receive modelform_instance.cleaned_data['ManyToMany field'] in view when form field is ModelMultipleChoiceField?

查看:102
本文介绍了当表单字段为ModelMultipleChoiceField时,如何在视图中接收modelform_instance.cleaned_data ['ManyToMany field']?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是情况:

我的模型如下:

class School(Model):
        name = CharField(...)

许可模型包含三个对象:

Permit model has three objects:

School.objects.create(name='school1')  # id=1
School.objects.create(name='school2')  # id=2

我有另一种型号:

Interest(Model):
    school_interest = ManyToManyField(School, blank=True,)

然后我使用兴趣构建一个ModelForm:

I then build a ModelForm using Interest:

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中,我拥有:

and in interest_template.html I have:

<form method="post">
    {% csrf_token %}
    {{ interest_form.as_p }}
<button type="submit">Submit</button>
</form>

我希望在不检查任何一个表单字段并提交时看到无".

I expect to see None when I check no one of the form fields and submit it.

当我检查任何或所有表单字段并提交表单时,我希望看到'Not None'.

I expect to see 'Not None' when I check any or all of the form fields and submit the form.

但是,我看不到预期的事情.

However, I do not see what I expect to happen.

推荐答案

我对此更改了看法,并且有效:

I changed my view to this and it worked:

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)

这篇关于当表单字段为ModelMultipleChoiceField时,如何在视图中接收modelform_instance.cleaned_data ['ManyToMany field']?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆