The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind

--

Chapters
00:00 Django: How To Save The Post.Get Of A Checkbox As False (0) In A Database?
01:29 Accepted Answer Score 16
02:15 Answer 2 Score 2
02:26 Answer 3 Score 1
02:41 Answer 4 Score 1
03:20 Thank you

--

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

--

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()