How to get Boolean values from request.POST dict How to get Boolean values from request.POST dict django django

How to get Boolean values from request.POST dict


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


How would django know that these questions are radio button input? It's all the same for Django because other form input answers are all sent in text format.

The right way to transform these values to right data types is through Django forms. You create a form for the answers you would like and when it is "clean"ed, it will be in right format. Check out Django's own forms documentation.

You should have something like:

   form = MyForm(request.POST)   if form.is_valid():         status = form.cleaned_data['sam_status']

Note that django form in the background will do what you have said, it will basically go through data and normalize them according to form definitions. But even when the form is very big, it shouldn't cause much of a performance trouble. If it is very slow, I advise you to check other code you have for performance bottlenecks.


Why don't you encode your data in JSON when you post it? Like this:

$.ajax({  url:url,  type:"POST",  data:data,  contentType:"application/json; charset=utf-8",  dataType:"json",  success: function(){    ...  }});

Then, if you decode the response body in Django, everything will be fine:

requestPost = json.loads(request.body.decode('utf-8'))