The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow

--

Chapters
00:00 Question
01:42 Accepted answer (Score 15)
02:34 Answer 2 (Score 2)
02:44 Answer 3 (Score 1)
03:29 Answer 4 (Score 1)
03:43 Thank you

--

Full question
https://stackoverflow.com/questions/3971...

Accepted answer links:
[Django ModelForm]: https://docs.djangoproject.com/en/1.10/t...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #djangomodels #djangoviews

#avk47



ACCEPTED ANSWER

Score 16


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.




ANSWER 2

Score 2


completed = request.POST.get('completed')
completed = True if completed else False



ANSWER 3

Score 1


Use this code snippet

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



ANSWER 4

Score 1


To tackle that problem you have to know how checkboxes work: if they are checked, a value is passed to request.POST -- but if a checkbox isn't checked, no value will be passed at all. So if the statement

'completed' in request.POST

is true, the checkbox has been checked (because only then 'completed' has been sent and is in the POST array), otherwise it hasn't.

I like this way more because it doesn't deal w/ any fancy default values, but is a plain and simple condition.

completed = 'completed' in request.POST
toSave = models.myClass( completed = completed )
toSave.save()