Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Boolean values from request.POST dict

I am using django 1.4 and I received parameters in request.POST.dict() which contain all values into Unicode format. Such as

{u'sam_status': u'true', u'address_type': u'false', u'is_deleted': u'false', u'title': u'true'}

But these values should be Boolean as they rendered from radio buttons from HTML page.

I want to convert this request.POST.dict() into a simple python dict which will have pythonic values such as for 'true'/'false' ==> True/False.

Note: I don't want apply for loop because this may impact the performance as this works on huge data.

like image 201
CrazyGeek Avatar asked Jan 22 '14 10:01

CrazyGeek


1 Answers

Having read the comments, the way you're doing it (not using Django forms, accepting POST requests from third party web apps and chosing to serialise the inputs as u"true" and u"false") you have no option but to loop over the POST dictionary keys and convert the strings to bools manually in python. If this is really that much of a performance impact then it may be time to rethink your approach.

Out of curiousity, who is designing the forms that you're accepting and serialising? Are you even doing the serialising or are they? And what are you doing in terms of security? "generic REST API model form submission" and "third party web apps" sounds like a recipe for disaster.

Edit: Please don't use eval() to convert u"False" into False

>>> for key, value in request.POST.items():
...     if value == u'true':
...         a[key] = True
...     if value == u'false':
...         a[key] = False
like image 187
ptr Avatar answered Sep 20 '22 05:09

ptr