how to receive modelform_instance.cleaned_data['foreign key field'] in view?

627 Views Asked by At

Here is the situation:

I have a model as below:

class Permit(Model):
        permit_option = BooleanField()

Permit model has two objects:

Permit.objects.create(permit_option=False)  # id=1
Permit.objects.create(permit_option=True)  # id=2

I have another model:

Interest(Model):
    permit_interest = ForeignKey(Permit, default=True, null=True, blank=True, on_delete=CASCADE, )

I then build a ModelForm using Interest:

class InterestForm(ModelForm):
    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['permit_interest'] == 2:
                return HttpResponse('True')
             elif interest_form.cleaned_data['permit_interest'] == 1:
                return HttpResponse('False')
             else:
                return HttpResponse('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 True when I choose True in the form field and submit it.

Or see False when I choose False in the form field and submit it.

What I have Tried:

I have tested numerous methods:

    if request.POST:
        interest_form = InterestForm(request.POST)
        if interest_form.is_valid():
             if interest_form.cleaned_data['permit_interest'] == True:
                return HttpResponse('True')
             elif interest_form.cleaned_data['permit_interest'] == False:
                return HttpResponse('False')
             else:
                return HttpResponse('None')

or

    if request.POST:
        interest_form = InterestForm(request.POST)
        if interest_form.is_valid():
             if interest_form.cleaned_data['permit_interest'] == 'True':
                return HttpResponse('True')
             elif interest_form.cleaned_data['permit_interest'] == 'False':
                return HttpResponse('False')
             else:
                return HttpResponse('None')

or

    if request.POST:
        interest_form = InterestForm(request.POST)
        if interest_form.is_valid():
             if interest_form.cleaned_data['permit_interest'] == '2':
                return HttpResponse('True')
             elif interest_form.cleaned_data['permit_interest'] == '1':
                return HttpResponse('False')
             else:
                return HttpResponse('None')

None of them returned my expected behaviour and I dont seem to understand what is going on in here and what I have to do.

2

There are 2 best solutions below

4
Maulik Harkhani On BEST ANSWER

views

When you are doing clean method for foreignkey they will provide foreignkey object so using object you can check permit_option field value and permit_option is boolean field so in python compare condition you need to give boolean value like True or False

or

on compare condition you can also use as id

instance_Interest.id == 1:

    if request.POST:
        interest_form = InterestForm(request.POST)
        if interest_form.is_valid():
             instance_Interest = interest_form .cleaned_data['permit_interest']

             if instance_Interest:
                pass
             else:
                return HttpResponse('None')


             if instance_Interest.permit_option == True:
                return HttpResponse('True')
             elif instance_Interest.permit_option == False:
                return HttpResponse('False')
             else:
                return HttpResponse('None')
0
Amit On

Changed the code very slightly. See if it works.

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['permit_interest'] == 'true': 
            return HttpResponse('True') 
        elif interest_form.cleaned_data['permit_interest'] == 'false': 
            return HttpResponse('False') 
# rest of the code is unchanged

You may try this. You can also try to print and see what value is coming to you from cleaned form.

print(interest_form.cleaned_data['permit_interest)