Somewhere in my Django app, I make an Ajax call to my view
$.post("/metrics", {
'program': 'AWebsite',
'marketplace': 'Japan',
'metrics': {'pageLoadTime': '1024'}
});
in my python code, I have got
#require_POST
def metrics(request):
program = request.POST.get('program', '')
marketplace = request.POST.get('marketplace', '')
metrics = request.POST.get('metrics', '')
reportMetrics(metrics, program, marketplace)
the metrics() function in python is supposed to call reportMetrics() with these parameters which are then supposed to go in a log file. But In my log file, I do not see the 'pageLoadTime' value - probably because it is being passed in as a dictionary. In future I need to add more items to this, so it needs to remain a dictionary (and not a string like first two).
Whats the easiest way to convert this incoming javascript dictionary to python dictionary?
Send the javascript dictionary as json and import the python json module to pull it back out. You'll use json.loads(jsonString).
Edit - Added example
$.post("/metrics", {
data: JSON.stringify({
'program': 'AWebsite',
'marketplace': 'Japan',
'metrics': {'pageLoadTime': '1024'}
})
});
Then on the python side
import json
def metrics(request):
data = json.loads(request.POST.get('data'))
program = data.get('program','')
marketplace = data.get('marketplace','')
metrics = data.get('metrics','')
I don't really have a good way of testing this right now, but I believe it should work. You may also have to do some checking if a field is blank, but I believe .get() will handle that for you.
Related
I've hit a bit of a stumbling block with a Django project having added a chart to a page using Chart.js only to find that it relies on the data inputted being in JSON format. I've researched ways of converting Django object values into JSON, such as serializing and re-writing my views, but for a number of reasons these aren't ideal options for me. Is there a way to convert Django object data to JSON data within the JS script?
I have an 'Accelerator' Django model with five separate decimal fields which ultimately need to be converted to JSON to feature in the chart. For each object created, the value of each field is prone to change (they are determined by a method calculating the mean value of separate values inputted into a separate model). I have an 'accelerator_detail' HTML template which renders and displays the various values of individual objects created using the Accelerator model.
This template is heavily reliant on Django placeholders and Python logic calling on object values, which is one reason why I'm hesitant about attempting to serialize the Django objects as JSON within my views (presumably this would mean I would have to re-write this template).
I've shared some of the relevant code below to provide a better understanding. Currently, the data key in my JS script is populated with dummy data but this is where my Django object values need to be stored:
// One of my model fields which needs converting to JSON
class Accelerator(models.Model):
avg_mentorship = models.DecimalField(decimal_places=2, max_digits=3)
#property
def avg_mentorship(self):
quantity = Review.objects.filter(subject=self)
mentorship_result = Review.objects.filter(subject=self).aggregate(avg_mentorship=Avg('mentorship'))['avg_mentorship']
return mentorship_result if len(quantity) > 0 else 0
// My accelerator_detail view
def accelerator_detail(request, pk):
accelerator = get_object_or_404(Accelerator, pk=pk)
reviews = Review.objects.all()
context = {
'accelerator': accelerator,
'reviews': reviews,
}
return render(request, 'reviews/accelerator_detail.html', context)
// JS script within my HTML template
<script>
var myChart = document.getElementById('accRatings').getContext('2d');
var ratingsChart = new Chart(myChart, {
type:'horizontalBar',
data:{
labels:['Mentorship', 'Hiring', 'Community', 'Fundraising', 'Corporate Development'],
datasets:[{
data:[
4.1,
4.4,
3.9,
3.6,
4.2
],
}]
},
});
</script>
Sorry I can't give this in a comment yet, have you looked into this yet? Django Generic JSON views. Seems to me like it would fit nicely into your project and help with the output you need.
Your data is already output by the view. You can just convert to JSON as you serve it from within the view.
Great example provided by SimpleIsBetterThenComplex:
from django.http import JsonResponse
def profile(request):
data = {
'name': 'Vitor',
'location': 'Finland',
'is_active': True,
'count': 28
}
return JsonResponse(data)
import requests
import math
api_addr = 'http://api.openweathermap.org/data/2.5/weather?appid=5da47c441c88cfac88086c508e1aefab&q='
city = input ('City Name? ')
url = api_addr+city
js_dat = requests.get(url).json()
This is my python code, this program basically pulls out some weather info. On the JavaScript end, I have not made a script yet.
I wanted to ask if I can use data from js_dat which will contain data in the json format, in JavaScript.
Thank you = )
PS: ignore the input function. I need an input from JS.
I am making a website using Django and I want to pass a python object from my view (where it is created) through the Django template and to a Dajax call. The problem is that by the time it gets to dajax it has been turned into type unicode.
In my Template
<script>
var emailer = "{{emailer|safe}}"; <---If I omit the quotes here then I get a javascript error.
sessionStorage.setItem('emailer',emailer);
$(document).ready(function(){
$('.send').on('click', function(e){
var emailer = sessionStorage.getItem('emailer');
Dajaxice.InterfaceApp.sendEmail(submitverify,{'emailer':emailer});
});
});
</script>
The dajax function
#dajaxice_register(method='GET')
def sendEmail(emailer):
logger.warning("type: %s, %s" % (type(emailer),emailer))
email_body = "message"
emailer.addToMessage(email_body)
emailer.send()
message = "Email Sent"
return json.dumps({'message':message})
Here the logger statement returns: type: <type 'unicode'>, <Utils.SIMPL_Emailer instance at 0x103142ab8>. Is there any way to fix this so that I get my emailer object instead of a unicode string?
First try to understand what is happening:
On your template you're trying to save a Python object to a Javascript var:
var emailer = "{{emailer|safe}}";`
But it's not possible. When your template is rendered by Django what you really get is a call to object __str__() method and your Javascript will store the <Utils.SIMPL_Emailer instance at 0x103142ab8> value on your emailer var. And remember: this code run in the client browser. That's why you get an error when you remove the quotes.
To solve it you need to first serialize your emailer object (Turn it into something that could be represented as a String, for example, and then turned back to Python Object). But as pointed by Peter DeGlopper it is a very insecure approach. Never, ever deserialize an whole object that was public accessible. Instead send only the email data to your template. You can create a dictionary with this data, turn it into JSON (it's a serialization too, but this time you are serializating only data) and then pass it to your template.
So do not put your emailer on the template context. Instead create a dictonary and pass it to the template.
Then in your Python sendEmail(emailer) method you'll need to instanciate a new Emailer object and feed it with the data, like:
#dajaxice_register(method='GET')
def sendEmail(email_json):
email = json.loads(email_json) # email_json is a json with your email data only
logger.warning("type: %s, %s" % (type(email_json),email_json))
emailer = Emailer("<with all your params...>")
emailer.addToMessage(email.get('body'))
emailer.send()
message = "Email Sent"
return json.dumps({'message':message})
I'm sending a JS object from my front-end to my Java backend, and I'm passing a object like so, which contains different types
wrapperObject = {
JSONOBJ = {
'key': 'value'
},
id: '123',
date: 'exampledate'
}
My java backend then takes this wrapperObject and converts every field inside into a value inside of a hashmap Map. Whenever it reaches the JSONObject, however, it parses it and attempts to insert into the db and I reach a
bad SQL grammar []; nested exception is org.postgresql.util.PSQLException: No hstore extension installed.
What can I do about this, and is there a better way of approaching this?
It sounds like it may be as simple as adding the hstore extension. The PostgreSQL documentation for installation looks pretty straightforward:
Let me know if I'm missing something, hope this helps!
Having issues with Jade and the way the data is passed to it when it is rendered.
I am trying to save the data which is in [{key1: "val1", key2: "val2"}, ...}];
format but having issues as it shows up as the result below.
Result
key: xyz value:[{"artist":"Lady Gaga",...
This is the code I am working with on the server-side Node.js which is passing it fine ...
res.render('musics', {
title: 'site',
result: JSON.stringify(result)
});
This is the code I am having issues with because of the way I have to call result in jade...
script
function local (arr) {
var i;
i = "#{result}";
localStorage.setItem('xyz', i);
}
console.log('stored');
local();
The quotes around result are messing it up but without them I get an error for unexpected identifier...
Any suggestions or if it might be better to go an ajax route through Backbone(which is what I am using with the client-side) I am willing to, just to put some pointers out - the data is being scraped and through selections of a form post - so the data comes back after the post and is a on time transfer, so if I did an ajax call it would have to include the post and the get, otherwise i am not sure of how to receive it... maybe res.json(result) on the server side, but then the page needs to render somehow... Open to suggestions. Thanks! Ultimately I want it to go into localStorage without the " around everything.
your jade snippet should look like this then:
script!= "(function() {localStorage.setItem('xyz',JSON.stringify(" +result + ");})();"
by using != you tell jade to not escape the following content, and on the clientside you have to stringify again before puting your data to local storage.
As an improvement to #greelgork's answer:
This is for JSON array
script!= "(function() {var items = []; items = JSON.parse(localStorage.getItem('Stored_items')); console.log(JSON.stringify(items)); items.push(" + JSON.stringify(product) + "); localStorage.setItem('Stored_items', JSON.stringify(items)); })();"
Anyways, pushing an item into localStorage needs to be stringified before inserted into localStorage hence, #greelgorke's answer should be modified so:
single item
script!= "(function() {localStorage.setItem('xyz',JSON.stringify(result)); })();"
So the JSON.stringify is outside the string just like all the other javascript code is,
This is what I use in my project and it worx
Credit Push JSON Objects to array in localStorage
if usersList.length
script.
const userList = !{JSON.stringify(usersList)}
localStorage.setItem('xyz',JSON.stringify(userList))
const loader = document.querySelector(".loader");
loader.className +=" hidden";