2

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:

enter image description here

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

enter image description here

Any help on this will be great. Thanks in advance for any replies.

1 Answer 1

5

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. A Form 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks the worked, really appreciate the help. Yeah we have used forms in other sections of the code but I could not seem to get it to work when using Modals and needing to use JSON and JQuery to bring up the data. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.