Django: How to save the POST.get of a checkbox as false (0) in a DataBase?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Django: How To Save The Post.Get Of A Checkbox As False (0) In A Database?
01:18 Accepted Answer Score 16
01:52 Answer 2 Score 1
02:02 Answer 3 Score 1
02:35 Answer 4 Score 2
02:39 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()