how to receive modelform_instance.cleaned_data['ManyToMany field'] in view when form field is ModelMultipleChoiceField?

天涯浪子 提交于 2019-12-13 02:42:54

问题


Here is the situation:

I have a model as below:

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

Permit model has three objects:

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

I have another model:

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

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__'

I have a view:

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)

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.

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.


回答1:


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)


来源:https://stackoverflow.com/questions/57216492/how-to-receive-modelform-instance-cleaned-datamanytomany-field-in-view-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!