将布尔值从 Javascript 转换为 Django?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18178564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting Boolean value from Javascript to Django?
提问by user2492270
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:
我注意到当布尔数据从 javascript 发送到 Django 视图时,它被传递为“真”/“假”(小写)而不是“真”/“假”(大写)。这会导致我的应用程序出现意外行为。例如:
vote.js
投票.js
....
var xhr = {
'isUpvote': isUpvote
};
$.post(location.href, xhr, function(data) {
doSomething()
});
return false;
});
views.py
视图.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???
当我保存此投票并检查我的 Django 管理页面时,“isUpvote”始终设置为 True,无论是从 javascript 传递 true 还是 false。那么将 javascript 的“真/假”布尔值转换为 Django 的“真/假”值的最佳方法是什么???
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....
然后当我检查我的 Django 管理员时,它被保存为“True”!!!所以我想这意味着由于某种奇怪的原因,lowercaes "false" 被保存为 Django "True" 值......
采纳答案by Conor Patrick
Try this.
试试这个。
from django.utils import simplejson
def post(self, request, *args, **kwargs):
isUpvote = simplejson.loads(request.POST.get('isUpvote'))
回答by Zippp
probably it could be better to have 'isUpvote' value as string 'true' or 'false' and use json to distinguish its boolean value
将 'isUpvote' 值设为字符串 'true' 或 'false' 并使用 json 区分其布尔值可能会更好
import json
isUpvote = json.loads(request.POST.get('isUpvote', 'false')) # python boolean
回答by SaeX
I came accross the same issue (true/false by Javascript - True/False needed by Python), but have fixed it using a small function:
我遇到了同样的问题(Javascript 的真/假 - Python 需要真/假),但使用一个小函数修复了它:
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.
它可能对某人有用。
回答by Mesut Tasci
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.
如果我将以下 JSON 发送到服务器,布尔字段将作为 test("true", "false") 出现,我必须能够访问catalogues
as request.POST.getlist("catalogues[]")
。我也无法轻松进行表单验证。
var data = {
"name": "foo",
"catalogues": [1,2,3],
"is_active": false
}
$.post(url, data, doSomething);
Django request handler:
Django 请求处理程序:
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 stringand converting data to back to json at server side.
我通过将 json 数据作为字符串发送并在服务器端将数据转换回 json 来解决这个问题。
var reqData = JSON.stringify({"data": data}) // Converting to string
$.post(url, reqData, doSomething);
Django request handler:
Django 请求处理程序:
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 :)
现在我可以进行表单验证并且代码更干净:)
回答by woofmeow
Javascript way of converting to a Boolean is
转换为布尔值的 Javascript 方式是
//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 ?
你确定你做对了吗?
回答by Andreas Bergstr?m
Since Django 1.5 dropped support for Python 2.5, django.utils.simplejsonis no longer part of Django as you can use Python's built in json instead, which has the same API:
由于 Django 1.5 放弃了对 Python 2.5 的支持,django.utils.simplejson不再是 Django 的一部分,因为您可以改用 Python 的内置 json,它具有相同的 API:
import json
def view_function(request):
json_boolean_to_python_boolean = json.loads(request.POST.get('json_field'))
回答by Kiran Racherla
Another alternative is to use literal_eval() from ast(Abstract Syntax Tree) library.
另一种选择是使用 ast(Abstract Syntax Tree) 库中的literal_eval()。
In Javascript/jquery:
在 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,
在您的 Django 视图中,
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
回答by Sergio Guillen
You can pass the strings "true" or "false" to boolean only with
您只能将字符串“true”或“false”传递给布尔值
isUpvote = request.POST.get('isUpvote') == 'true'
回答by Aqueel Aboobacker VP
I usually convert JavaScript Boolean value into number.
我通常将 JavaScript 布尔值转换为数字。
var xhr = {
'isUpvote': Number(isUpvote)
};
In python:
在蟒蛇中:
try:
is_upvote = bool(int(request.POST.get('isUpvote', 0)))
except ValueError:
// handle exception here
回答by vbevans94
I have faced the same issue when calling django rest api from js, resolved it this way:
我在从 js 调用 django rest api 时遇到了同样的问题,解决方法如下:
isUpvote = request.POST.get("isUpvote")
isUpvote = isUpvote == True or isUpvote == "true" or isUpvote == "True"