I'm using a js function to obtain some data from my django models. Concretely, I want to obtain the last value from my sensors.
I'm doing the following,
from django.core import serializers
def getData(request):
ctx = {}
if request.method == 'POST':
select = int(request.POST['Select'])
last_val = DevData.objects.order_by('dev_id','-data_timestamp').distinct('dev_id')
data = serializers.serialize('json', last_val)
print(data)
print('****************')
print(data[0]) # I just obtain a "[" then is a string not a list
ctx = {'Select':data}
return JsonResponse(ctx)
My question is, why the output is a string? How can I convert it to a Json object and then pass it to my js function?
Thank you very much!!
You obtain a string, because JSON is a text format. You can for example use json.loads to convert it back to a list of dictionaries:
from json import loads as jsonloads
from django.core import serializers
def getData(request):
ctx = {}
if request.method == 'POST':
select = int(request.POST['Select'])
last_val = DevData.objects.order_by('dev_id','-data_timestamp').distinct('dev_id')
data = jsonloads(serializers.serialize('json', last_val))
ctx = {'Select':data}
return JsonResponse(ctx)
The JSON serialization in Django is just a special JsonEncoder named DjangoJSONEncoder [GitHub], that has some special cases for a datetime object, etc.
Related
Currently, my application is to select the stock data, then analyzing it by using another python script and output the result(in JSON format).
Now I would like to add a button to output the result(w_df_split) to CSV, then when the user clicks the button and download the csv file.
But I am stuck in how to return the output CSV function in this view.
views.py:
def efficient_frontier_select(request):
user_holding = Position.objects.filter(created_by = request.user)
selected_stock = None
w_df_split = None
if request.method == 'POST':
selected_stock = request.POST.getlist('stock_symbol')
ta, tb, tc = ef.combination_frontier(selected_stock)
fy_df, fx_df, w_df, fxfy_df, ef_df = ef.transform_frontier_todf(ta,tb,tc, selected_stock)
w_df_split = json.loads(ef.json_format_split(w_df))
context = {
'w_df_split' : w_df_split,
}
return render(request, 'portfolio/efficient_frontier.html', context)
Asumming df is a dataframe, you you could use pandas's df.to_csv(). Like that: csv_data = w_df.to_csv(). You could do the same to json with w_df.to_json()
Just an update!
Django view design - export CSV from user-generated content
This works by setting the hidden input field to store the JSON data.
I have the following view:
views.py
def PackingListView(request):
if request.method == "POST":
form = PackingListForm(request.POST)
if form.is_valid():
if 'preview' in request.POST:
request.session['data'] = form.cleaned_data
return redirect('myview')
....
I would like to take the data in form and pass it to this next view, and set the data variable equal to it. This was previously working, but once I added a foreign key into this form, the session no longer works as it is not serializable. What approach is the safest for me to take here?
views.py
class myview(View):
def get(self, request, *args, **kwargs):
data = request.session.pop('data', {})#this won't work now
pdf = render_to_pdf('packlist_preview.html', data)
return HttpResponse(pdf, content_type='application/pdf')
Also in case it is needed - here is the URL for myview
url(r'^myview/', views.myview.as_view(), name='myview'),
You should be able to serialize the data if you replace the model instance with its id.
data = form.cleaned_data
# remove object from data dict
related_object = data.pop('related_object')
# add in a reference
data['related_object_id'] = related_object.pk
# now you should be able to serialize object
request.session['data'] = data
Then in the next view, you can fetch the object from the database using its id
data = request.session.pop('data', {})
related_object_id = data.pop('related_object_id', None)
if related_object_id:
try:
data['related_object'] = RelatedObject.objects.get(pk=related_object_id)
except RelatedObject.DoesNotExist:
pass
I have three different fileds username,password and role if all these three values matches then user will be able to login else he will not be able to login.
import json
from django.db import models
from django.http import HttpResponse
from rest_framework import serializers
def loginemployee(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
payload = body['username']
passwordcheck = body['password']
rolecheck = body['role']
if payload:
employee=models.Employees.objects.filter(Q(username=payload['username']) & Q(password=passwordcheck['password']) & (Q(role=rolecheck['role']) | Q(backup_role=payload['role'])))
# employees1=models.Employees.objects.filter(Q(email=payload['username']) & Q(role=payload['role']))
# empl=(employee+employees1);
if employee:
emp = serializers.serialize('json', employee)
return HttpResponse(emp,content_type='application/json')
can you help me the fix the issue in the above code.
i am getting error message string indices must be integers
I'm using DJango 1.8 and Python 3.4
When the below view is being ran, Django throws Type Error - Object is not JSON Serializable
Views.py
from django.http import HttpRequest,HttpResponse
from django.http import JsonResponse
from json import dumps
def get_stats(request):
if request.method == "POST":
srch_dropV = request.POST['srch_dropAJ']
else:
srch_dropV = ''
if(srch_dropV == 'Green'):
students = GreenBased.objects.all()
if(srch_dropV == 'Yellow'):
students = YellowBased.objects.all()
response_data = {}
try:
response_data['result'] = 'Success'
response_data['message'] = list(students)
except:
response_data['result'] = 'Ouch!'
response_data['message'] = 'Script has not ran correctly'
return HttpResponse(JsonResponse(response_data), content_type="application/json")
I'm trying to read couple of rows from mysql database and display it on the html file, I'm facing below error message when above view is being ran
TypeError: YellowBased: YelloBased object is not JSON serializable
In HTML Page, I have a drop down list.. based on the option that is selected, my Ajax would return me the records that were fetched from mysql table.
Models.py
class GreenBased(models.Model):
NumOfStudents = models.CharField(max_length=300,blank=True)
Green = models.CharField(max_length=300,blank=True)
class Meta:
managed = False
db_table = "GreenStats"
class YelloBased(models.Model):
NumOfStudents = models.CharField(max_length=300,blank=True)
Yellow = models.CharField(max_length=300,blank=True)
class Meta:
managed = False
db_table = "YellowStats"
GreenStats and YellowStats tables contains only 2*2 rows in mysql
Can someone please help me to identify this issue ?
You have to serialize your student objects list, try something like this:
from django.http import HttpRequest,HttpResponse
from django.http import JsonResponse
from json import dumps
from django.core import serializers
def get_stats(request):
if request.method == "POST":
srch_dropV = request.POST['srch_dropAJ']
else:
srch_dropV = ''
if(srch_dropV == 'Green'):
students = GreenBased.objects.all()
if(srch_dropV == 'Yellow'):
students = YellowBased.objects.all()
response_data = {}
try:
response_data['result'] = 'Success'
response_data['message'] = serializers.serialize('json', students)
except:
response_data['result'] = 'Ouch!'
response_data['message'] = 'Script has not ran correctly'
return JsonResponse(response_data)
Notice the line change in :
response_data['message'] = serializers.serialize('json', students)
Also JsonResponse does the trick on its own, so no need to wrap it in a HttpResponse.
check the docs for more customization:
https://docs.djangoproject.com/en/1.8/topics/serialization/
Hope this helps!
I'm trying to convert bson data gotten straight from pymongo into json data. Is there a straight forward way to do this with python using pymongo or something else?
Here's the code if it helps:
def email_main(request):
collection = get_collection("nimbus").fullcontact_email_data
if request.method == "POST":
data = collection.save(dict(request.POST.iterlists()))
response = HttpResponse(data, content_type="application/json")
elif request.method == "GET":
getParams = convertQuerydictToDict(request.GET)
page, itemsPerPage = getPageDataFromDict(getParams)
getParamsWithNoPageData = createDictWithoutPageData(getParams)
data = collection.find(getParamsWithNoPageData)[page:page+itemsPerPage+1]
response = HttpResponse(data, content_type="application/json")
else:
response = HttpResponse(status=404)
return response
def convertQuerydictToDict(queryDict):
return dict(queryDict.iterlists())
def getPageDataFromDict(myDict):
if "page" in myDict and "itemsPerPage" in myDict:
page, itemsPerPage = myDict["page"], myDict['itemsPerPage']
elif "page" in myDict:
page, itemsPerPage = myDict["page"], 10
else:
page, itemsPerPage = 0, 10
return page, itemsPerPage
def createDictWithoutPageData(myDict):
newDict = deepcopy(myDict)
newDict.pop("page", None)
newDict.pop("itemsPerPage", None)
return newDict
basically that data variable needs to get turned into proper json. There must be some built in thing that does this.
For clarity here's what I get when I put data into the python console:
>>> data
<pymongo.cursor.Cursor object at 0x4dd0f50>
>>> data[0]
{u'blah': u'go', u'_id': ObjectId('540e3fd8bb6933764d5650b7')}
ObjectId is not part of the json spec...
As discussed in the comments above, it appears that the best approach is to use PyMongo's json_util module to handle the gory details of converting BSON to JSON.