I noticed that when Boolean data is sent from javascript to Django view, it is passed as "true"/"false" (lowercase) instead of "True"/"False"(uppercase). This causes an unexpected behavior in my application. For example:
vote.js
....
var xhr = {
'isUpvote': isUpvote
};
$.post(location.href, xhr, function(data) {
doSomething()
});
return false;
});
views.py
def post(self, request, *args, **kwargs):
isUpvote = request.POST.get('isUpvote')
vote, created = Vote.objects.get_or_create(user_voted=user_voted)
vote.isUp = isUpvote
vote.save()
when I save this vote and check my Django admin page, "isUpvote" is ALWAYS set to True whether true or false is passed from javascript. So what is the best way to convert javascript's "true/false" boolean value to Django's "True/False" value???
Thanks!!
ADDED:::::
Well, I added some 'print' lines to check whether I was doing something wrong in my view:
print(vote.isUp)
vote.isUp = isUpvote
print(vote.isUp)
vote.save()
The result:
True
false //lowercase
And then when I check my Django admin, it is saved as "True"!!! So I guess this means lowercaes "false" is saved as Django "True" value for some weird reason....
11 Answers 11
probably it could be better to have 'isUpvote' value as string 'true' or 'false' and use json to distinguish its boolean value
import json
isUpvote = json.loads(request.POST.get('isUpvote', 'false')) # python boolean
Comments
Try this.
from django.utils import simplejson
def post(self, request, *args, **kwargs):
isUpvote = simplejson.loads(request.POST.get('isUpvote'))
1 Comment
I encounter the same problem and I solved the problem with more clear way.
Problem:
If I send below JSON to server, boolean fields come as test("true", "false") and I must be access to catalogues as request.POST.getlist("catalogues[]"). Also I can't make form validation easly.
var data = {
"name": "foo",
"catalogues": [1,2,3],
"is_active": false
}
$.post(url, data, doSomething);
Django request handler:
def post(self, request, **kwargs):
catalogues = request.POST.getlist('catalogues[]') # this is not so good
is_active = json.loads(request.POST.get('is_active')) # this is not too
Solution
I get rid of this problems by sending json data as string and converting data to back to json at server side.
var reqData = JSON.stringify({"data": data}) // Converting to string
$.post(url, reqData, doSomething);
Django request handler:
def post(self, request, **kwargs):
data = json.loads(request.POST.get('data')) # Load from string
catalogues = data['catalogues']
is_active = data['is_active']
Now I can made form validation and code is more clean :)
Comments
I came accross the same issue (true/false by Javascript - True/False needed by Python), but have fixed it using a small function:
def convert_trueTrue_falseFalse(input):
if input.lower() == 'false':
return False
elif input.lower() == 'true':
return True
else:
raise ValueError("...")
It might be useful to someone.
Comments
Javascript way of converting to a Boolean is
//Your variable is the one you want to convert var myBool = Boolean(yourVariable);
However in your above code you seem to be passing a string instead of the variable here
isUpvote = request.POST.get('isUpvote')
Are you sure you are doing it correctly ?
2 Comments
isUpvote = request.POST.get('isUpvote') and vote, created = Vote.objects.get_or_create(user_voted=user_voted) . I think you are treating isUpvote as a string when sending the request. Im not sure if thats the way its done in django. Also rememeber that you are sending an object xhr in your request. Try looking online at how to access object properties. Thats as much I can do ... feel free to accept the answer if it helps.Since Django 1.5 dropped support for Python 2.5, django.utils.simplejson is no longer part of Django as you can use Python's built in json instead, which has the same API:
import json
def view_function(request):
json_boolean_to_python_boolean = json.loads(request.POST.get('json_field'))
Comments
With Python's ternary operator:
isUpvote = True if request.POST.get("isUpvote") == "true" else False
Also I should mention that if you are working with Django's forms and are trying to pass compatible Boolean value to the Form or ModelForm class via Ajax, you need to use the precise values Django is expecting.
Assuming null=True on your model:
- Unknown
- Yes (True)
- No (False)
So for example, the following would deliver Boolean data to Django's form properly:
<input type="radio" id="radio1" name="response" value="2">
<label for="radio1">Yes</label>
<input type="radio" id="radio2" name="response" value="3">
<label for="radio2">No</label>
1 Comment
I have faced the same issue when calling django rest api from js, resolved it this way:
isUpvote = request.POST.get("isUpvote")
isUpvote = isUpvote == True or isUpvote == "true" or isUpvote == "True"
1 Comment
Another alternative is to use literal_eval() from ast(Abstract Syntax Tree) library.
In Javascript/jquery:
$.ajax({
url: <!-- url for your view -->,
type: "POST",
data: {
is_enabled: $("#id_enable_feature").prop("checked").toString() <!-- Here it's either true or false>
}
})
In your Django view,
from ast import literal_eval
def example_view(request):
is_enabled = literal_eval((request.POST.get('is_enabled')).capitalize())
print(is_enabled) # Here, you can check the boolean value in python like True or False
Comments
I usually convert JavaScript Boolean value into number.
var xhr = {
'isUpvote': Number(isUpvote)
};
In python:
try:
is_upvote = bool(int(request.POST.get('isUpvote', 0)))
except ValueError:
// handle exception here
Comments
You can pass the strings "true" or "false" to boolean only with
isUpvote = request.POST.get('isUpvote') == 'true'
Comments
Explore related questions
See similar questions with these tags.
isUpvoteis the string"true"(or"false") and set the appropriate value.