开发者

django post checkbox data

开发者 https://www.devze.com 2023-03-10 06:59 出处:网络
I\'m usin开发者_C百科g a checkbox form in my template and in my view im trying to check if the box has been checked or not

I'm usin开发者_C百科g a checkbox form in my template and in my view im trying to check if the box has been checked or not I have the following code in my view:

if request.POST['check'] == True:

but then it throws an error if it is unchecked. How do i check if there is a value 'check' in my post data?

Thanks


The Python docs are your friend:

 if request.POST.get('check', False):
     ...do stuff...

You could also do this (more Python docs):

 if "check" in request.POST:
     ... do stuff...


This is what I did:

request.POST.get('field_name', '') == 'on'

Note: another proposed solution

request.POST.get('check', False) # do not use it

led to this error for me:

['“on” value must be either True or False.']

when the checkbox is selected.

0

精彩评论

暂无评论...
验证码 换一张
取 消