CrazyGeek CrazyGeek -4 years ago 188
Python Question

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download