SuperCow SuperCow - 9 months ago 64
Python Question

Django: How to save the POST.get of a checkbox as false (0) in a DataBase?

I'm trying to save the value of a checkbox as true or false in a database. I have to use a model for this. If the box is checked the value of '1' is saved. However, if the box is not checked I get the error message:

Django Version: 1.9.4
Exception Type: IntegrityError
Exception Value: (1048, "Column 'completed' cannot be null")

Currently my setup looks like this:

In I have:

class myClass(models.Model):
completed = models.BooleanField(default=False, blank=True)

In I have:

def create_myClass(request):
completed = request.POST.get('completed')
toSave = models.myClass(completed=completed)

and in the HTML I have:

<label class="col-md-5" for="completed"> Completed: </label>
<input id="completed" type="checkbox" name="completed">

I've tried to set required = False in the BooleanField as some other posts suggested but then get the error:
TypeError: __init__() got an unexpected keyword argument 'required'

I've also tried to set 'completed' to False in like:

if request.POST.get('completed', False ):
commpleted = False


completed = request.POST.get('completed')
if completed == 'null':
commpleted = False

But neither work (not sure if my syntax is correct?)

Any ideas or suggestions are greatly appreciated!

Answer Source

You can print the value of request.POST to see what you are getting in the views.

If you have not specified a value attribute in the checkbox HTML element, the default value which will passed in the POST is on if the checkbox is checked.

In the views you can check if the value of completed is on:

# this will set completed to True, only if the value of 
# `completed` passed in the POST is on 
completed = request.POST.get('completed', '') == 'on'

If the checkbox is not checked, then nothing will be passed and in that case you will get False from above statement.

I would suggest that you use a Django ModelForm if you can so most of the things are automatically taken care for you.