-->

how to receive modelform_instance.cleaned_data[

2019-08-20 04:23发布

问题:

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)