SuperCow SuperCow - 7 days ago 4
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 models.py I have:

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


In views.py I have:

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


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 views.py like:

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


and

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!

AKS AKS
Answer

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.