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()
Boolean FunctionThe Boolean() will return true for any non-empty, non-zero, object, or array. If the first parameter is 0, -0, null, false, NaN, undefined, '' (empty string), or no parameter passed then the Boolean() function returns false . The new operator with the Boolean() function returns a Boolean object.
To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.
If you don't pass it, False will be the default value passed. Same way you pass any other parameter. Booleans aren't special. Why do you make it a string? There's nothing special about True or False values... If what you mean is how to pass specific parameters but not others, Python has "keyword parameters":
A boolean is a primitive value that represents either true or false. In Boolean contexts, JavaScript utilizes type casting to convert values to true/false. There are implicit and explicit methods to convert values into their boolean counterparts.
The bool () function allows you to evaluate any value, and give you True or False in return, Almost any value is evaluated to True if it has some sort of content.
If what you mean is how to pass specific parameters but not others, Python has "keyword parameters": def foo (a, b=1, c=False): print (a, b, c) foo (1) # b will be 1 and c False (default values) foo (1, c=True) # b will be 1 (default) and c True Python also allows to specify keyword arguments dynamically... for example
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With