20

The following seems to pass a string instead of a boolean value. How would I pass a boolean?

$.post('/ajax/warning_message/', {'active': false}, function() {
            return
       });
def warning_message(request):
    active  = request.POST.get('active')
    print active
    return HttpResponse()

3 Answers 3

61

In your Python code do this:

active = True if request.POST.get('active') == 'true' else False

Or even simpler:

active = request.POST.get('active') == 'true'

Be aware that the get() function will always return a string, so you need to convert it according to the actual type that you need.

Sign up to request clarification or add additional context in comments.

1 Comment

I would suggest the following for ease of reading active = request.POST.get('active', False) == 'true'
7

Assuming that you could send boolean value to the server as true/false or 1/0, on the server-side you can check both cases with in:

def warning_message(request):
    active = request.POST.get('active') in ['true', '1']
    print active
    return HttpResponse()

Otherwise, if you are sure that your boolean will be only true/false use:

def warning_message(request):
    active = request.POST.get('active') == 'true'
    print active
    return HttpResponse()

2 Comments

An argument could be made that you should just pick either "true" or "1" and only accept that one value, but this is a good solution if you want both.
@BrendanLong Yes, that's my thoughts as well.
1

The answer by Oscar is a 1-liner and I'd like to take nothing from it but, comparing strings is not the cleanest way to do this.

I like to use the simplejson library. Specifically loads parses the natural json form of JavaScript to native Python types. So this technique can be used for a wider set of cases.

This will give you uniform code techniques which are easier to read, understand & maintain.

From the docs:

Deserialize s (a str or unicode instance containing a JSON document) to a Python object.

import simplejson as sjson
valid_python_var = sjson.loads(json_str_to_parse)

Or in the likely scenario that you are receiving it via parameter passing:

var_to_parse = request.POST.get('name_of_url_variable') #get url param
    if var_to_parse is not None: #check if param was passed, not required
        parsed_var = sjson.loads(var_to_parse) # loads does the work

Note: Import libraries using common sense, if you are going to use them once there is no need for it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.