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.