Reputation: 125
I have a ModelForm which has Boolean Field and CheckboxInput. The Boolean field provides values of 0 (False) & 1 (True) by default in the MYSQL Database.
The form is a modal and uses JSON to output the content from the Model. When the JSON file adds the content it enters either True or False.
The issue occurs when I try to change and submit the value of the Checkbox Input from False to True. When I try this I get the following message:
Oddly this works the other way around and allows me to submit the change from True to False.
Below is the code (I have only included the field with the issue.) The field is First_Time_Booking
Model.
first_time_booking = models.BooleanField()
Form Widget.
'first_time_booking': CheckboxInput(attrs={'class': 'form-check-input', 'id': 'bfbw_edit_first_time_booking', 'name': 'bfbw_edit_first_time_booking'}),
View
def update_bfbw(request):
if request.method == 'POST':
bfbw_booking_id = request.POST.get('bfbw_booking_ref')
bfbw_data = BFBWBookings.objects.get(id=bfbw_booking_id)
bfbw_data.school_name = request.POST['school_name']
bfbw_data.first_time_booking = request.POST.get('first_time_booking', False)
bfbw_data.save()
else:
print(form.errors)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
I have tried writing an If function to alter the value, this then works to change the value to On but not when switching it off. I then get the below message.
if request.POST['first_time_booking'] == 'on':
bfbw_data.first_time_booking = True
else:
bfbw_data.first_time_booking = False
Any help on this will be great. Thanks in advance for any replies.
Upvotes: 2
Views: 6610
Reputation: 477844
The value is either "on"
(if the user has checked the checkbox), or does not exists (if the user has not checked the checkbox).
You thus can work with:
bfbw_data.first_time_booking = request.POST.get('first_time_booking') == 'on'
Note: It is better to use a
Form
[Django-doc] than to perform manual validation and cleaning of the data. AForm
will not only simplify rendering a form in HTML, but it also makes it more convenient to validate the input, and clean the data to a more convenient type.
Upvotes: 5