Converting a boolean value from Javascript to Django?

I noticed that when boolean data is sent from javascript to the Django view, it is passed as "true" / "false" (lower case) instead of "True" / "False" (upper case). This causes unexpected behavior in my application. For instance:

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 voice and check my Django admin page, "isUpvote" ALWAYS sets to True whether true or false is passed from javascript. So what is the best way to convert javascript "true / false" boolean value to Django value "True / False" ???

Thanks!!

ADDED :::

Well, I added a few lines of "print" to verify that I was doing something wrong:

  print(vote.isUp) vote.isUp = isUpvote print(vote.isUp) vote.save() 

Result:

  True false //lowercase 

And then when I check my Django admin, it is saved as "True" !!! Therefore, I assume that this means that subordinate “false” ones are stored as Django's “True” value for some strange reason ....

+8
source share
9 answers

Try it.

 from django.utils import simplejson def post(self, request, *args, **kwargs): isUpvote = simplejson.loads(request.POST.get('isUpvote')) 
+4
source

perhaps it would be better to have the value isUpvote as the string "true" or "false" and use json to distinguish its boolean value

 import json isUpvote = json.loads(request.POST.get('isUpvote', 'false')) # python boolean 
+7
source

I ran into the same problem (true / false by Javascript - True / False required by Python), but fixed it with a little function:

 def convert_trueTrue_falseFalse(input): if input.lower() == 'false': return False elif input.lower() == 'true': return True else: raise ValueError("...") 

It may be helpful to someone.

+4
source

I am facing the same problem and I solved the problem in a more understandable way.

Problem:

If I send below JSON to the server, the boolean fields come as test ("true", "false"), and I should have access to catalogues as request.POST.getlist("catalogues[]") . Also I cannot simplify form validation.

 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 

Decision

I get rid of these problems by sending json data as string and converting the data back to json on the 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 do form validation, and the code is cleaner :)

+3
source

Javascript way to convert to logical

  // Your variable is the one you want to convert
 var myBool = Boolean (yourVariable); 

However, in your previous code, you seem to pass a string instead of a variable here

  isUpvote = request.POST.get ('isUpvote')

Are you sure you are doing it right?

+1
source

Since Django 1.5 has stopped supporting Python 2.5, django.utils.simplejson is no longer part of Django, since instead you can use Python built in to json, which has the same API:

 import json def view_function(request): json_boolean_to_python_boolean = json.loads(request.POST.get('json_field')) 
+1
source

With Python, the ternary operator :

 isUpvote = True if request.POST.get("isUpvote") == "true" else False 

Also, I should mention that if you are working with Django forms and trying to pass a compatible boolean value to the Form or ModelForm class through Ajax, you need to use the exact values ​​expected by Django.

Assuming null=True on your model:

  1. Unknown
  2. Yes true)
  3. No (False)

So, for example, the following will correctly deliver the logical data to the Django form:

 <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> 
0
source

I usually convert a boolean JavaScript value to a number.

 var xhr = { 'isUpvote': Number(isUpvote) }; 

In python:

 try: is_upvote = bool(int(request.POST.get('isUpvote', 0))) except ValueError: // handle exception here 
0
source

I ran into the same problem when calling django rest api from js, solved it like this:

 isUpvote = request.POST.get("isUpvote") isUpvote = isUpvote == True or isUpvote == "true" or isUpvote == "True" 
0
source

Source: https://habr.com/ru/post/951525/


All Articles