I'm trying to learn django/python and I'm trying to figure out how to read json data...
I have something like :
{
region: {
span: {
latitude_delta: 0.08762885999999526,
longitude_delta: 0.044015180000002374
},
center: {
latitude: 37.760948299999995,
longitude: -122.4174594
}
},...
}
I'm trying to read specific data in my html page. Right now this json data is being displayed in the html page.
The source of the this json comes from this:
return HttpResponse(json.dumps(response),mimetype="application/json")
I'm trying to figure out the django/python convention of getting specific data? Am I supposed to do a for each loop? I come from a self taught php background, and I'm trying to teach myself python/django.
Thank you
edit:
I also have this in my view.py before the return HttpResponse
try:
conn = urllib2.urlopen(signed_url, None)
try:
response = json.loads(conn.read())
finally:
conn.close()
except urllib2.HTTPError, error:
response = json.loads(error.read())
This is the easiest way to read json in html (Send by Django)
def sendJson(request):
if request.method == 'GET':
context = {"name":"Json Sample Data"}
return render_to_response('name.html',context)
Django Template Html Code
<div class="col-md-9 center">
<span class="top-text">{{name}}</span>
</div>
Now according to your:
def sendJson(request):
if request.method == 'GET':
jsonData = {
region: {
span: {
latitude_delta: 0.08762885999999526,
longitude_delta: 0.044015180000002374
},
center: {
latitude: 37.760948299999995,
longitude: -122.4174594
}
}
}
data = json.dumps(jsonData)
return HttpResponse(data, content_type="application/json")
you can read this data by using jquery also
another example to create json and read in html
url.py
url(r'^anotherexample/$', 'views.anotherexample', name="anotherexample"),
view.py
def anotherexample(request):
if request.method == 'POST':
_date = strftime("%c")
response_data = {}
response_data['status'] = 'taken'
response_data['issueTakenTime'] = _date
return HttpResponse(json.dumps(response_data), content_type="application/json")
Html view and jquery
$.ajax({
url: "/anotherexample/",
// contentType: "application/json; charset=UTF-8",
data: { csrfmiddlewaretoken: "{{ csrf_token }}", // < here
status : "taken"
},
type: "POST",
error: function(res) {
console.log("errr", res)
},
success: function(res) {
console.log("res", res)}
})
It's not clear what you want to loop over, where, or how, but basic loops work like this:
data = {"key1":[1,2], "key":[4,5]}
for key, values in data.iteritems():
print key, values
I was able to figure out the solution through this link: Decode json and Iterate through items in django template
It helped me and hopefully it'll help someone else who has the same problem as me.
Thanks
Related
I tried to get the data I send via Ajax with request.GET.get, but this does not work. Data is always None. I really appreciate any kind of help!
This is my jQuery/Ajax code:
$(document).ready(function(){
$(".jcf-select.jcf-unselectable").on('click', function(){
var sel = $('#sort').children("option:selected").val();
console.log(sel)
$.ajax({
url: '/filter-data',
data: sel,
dataType: 'json',
success:function(res){
console.log(res);
$("#filter_products").html(res.order);
}
});
});
});
This is my view:
def filter_data(request):
if request.is_ajax:
query = []
data = request.GET.get('data')
if data == "gpv":
query = data.order_by("price_with_shipping")[:150]
elif data == "gp":
query = data.order_by("lowest_price")[:150]
elif data == "lp":
query = data.order_by("liter_price")[:150]
elif data == "tz":
query = data.order_by("-lowest_price")[:150]
t = render_to_string('homepage/ajax-products.html', {'order': query})
return JsonResponse({'order': t})
data must be an object in ajax.
for example:
$.ajax({
url: '/filter-data',
data: {'key-data':sel},
dataType: 'json',
success:function(res){
console.log(res);
$("#filter_products").html(res.order);
}
and in your django veiw:
data = request.GET.get('key-data')
I'm trying change Ajax json url to python variable with a json in Django. As you can see the url in both cases are the same so I can't understand what is going on.
Thanks in advance.
What I'm looking for and does not work
<script>
$(document).ready(function() {
var table = $('#users').DataTable({
"ajax": "{{ es_docs }}",
my view:
#login_required(login_url="/login/")
def index(request):
context = {}
context['segment'] = 'index'
html_template = loader.get_template( 'index.html' )
resp = requests.get("https://gyrocode.github.io/files/jquery-datatables/arrays_id.json").json()
context['es_docs'] = resp
return HttpResponse(html_template.render(context, request))
Template.html:
<script>
$(document).ready(function() {
var table = $('#users').DataTable({
"ajax": "https://gyrocode.github.io/files/jquery-datatables/arrays_id.json",
'columnDefs': [
{
'targets': 0,
'checkboxes': {
'selectRow': true
}
}
],
'select': {
'style': 'multi'
},
'order': [[1, 'asc']]
});
This:
resp = requests.get(...)
Returns a response object. To get the json data do this:
response = requests.get(...)
if response.status_code != 200:
# handle errors:
else:
json_data = response.json()
context['es_docs'] = json_data
Updated Question:
Wrong redirection of URL in Django. I have this:
views.py.
def graph(request):
if request.method == 'POST' and 'text' in request.POST:
print("testing....")
print(request.POST.get('text'))
name = request.POST.get('text')
context = {
'name': name,
}
print(context)
return render(request, 'StockPrediction/chart.html', context)
else:
return render(request, 'StockPrediction/greet.html')
urls.py
urlpatterns = [
path("", views.greet, name='greet'),
path("index/", views.index, name='Stock Prediction'),
path("prediction/", views.prediction, name='Prediction'),
path("view/", views.graph, name='Graph'),
]
for testing purposes, I m using a print statement. So there is no problem until printing print(context) but the problem is it goes to 'StockPrediction/greet.html' not 'StockPrediction/chart.html'. which I need.
You should use ajax request:
$.ajax({
type: 'POST',
url: 'YOUR VIEW URL',
data: {'row': row, 'text': text},
success: function (data){
DO SOMETHING HERE if VIEW has no errors
})
in your view:
row = request.POST.get('row')
text = request.POST.get('text')
also you should care about crsf-token. Documentation
your can POST it GET it or put it as a variable in your url. here is a post approach:
using jquery :
$.ajax({
url : "/URL/to/view",
type : "POST", // or GET depends on you
data : { text: $text },
async: false,
// handle a successful response
success : function(json) {
// some code to do with response
}
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
In your view you can get the data as json and return josn as response
import json
def my_view(request):
if request.method == 'POST':
response_data = {} // to return something as json response
text = request.POST['text']
...
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
else:
return HttpResponse(
json.dumps({"nothing to see": "this isn't happening"}),
content_type="application/json"
)
I have two different AJAX requests that I want to combine.
The first one gets some html:
def ajax_get_html(request):
if request.is_ajax() and request.method == "POST":
context = {
...
}
return render(request,"my_app/my_template.html", context)
else:
raise Http404
And is used like this:
$.ajax({
type: "POST",
url: ajax_url,
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
$(my_div).html(data);
}
});
My second one gets some data:
def ajax_get_data(request):
if request.is_ajax() and request.method == "POST":
data = {
"answer": 42,
}
json_data = json.dumps(data)
return HttpResponse(json_data, content_type='application/json')
else:
raise Http404
and is used like this:
$.ajax({
type: "POST",
url: another_ajax_url,
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
var answer = data.answer;
$("#notification_badge").html(answer);
}
});
How can I combine these to into the same request? I tried adding the result of render to the data in the second view, but json.dumps says it's non serializable.
You can't serialize the output of Django's render because it returns an HttpResponse object, not a string (which is what you want to be able to serialize it).
A good solution is to return your html to the frontend using render_to_string:
...
data = {
"answer": 42,
"html": render_to_string("my_app/my_template.html", context)
}
...
I have a JSON data that I sent to my server using AJAX. The data comes here and I see it.
def add_collection(self):
form = AccountForm.LoginForm(request.form)
if self.request.method == 'GET' :
return render_template('add_collection.html',user=current_user,formLogin = form)
elif self.request.method == 'POST' :
for data in self.request.data :
print "The data is %s" %data
When I print self.request.data I get my JSON like
[{"image":"https://mybucket.s3.amazonaws.com/asma.jpg","Description":"Photo Descriptiong"},
{"image":"https://mybucket.s3.amazonaws.com/NCg3G.png","Description":"Photo Description"}]'
The above is exactly what my JSONfile looks like and what I am expecting. However, I want to break it into the two rows and insert into the database. Please how do i loop through JSON. I have seen similar questions here and many more. However, none works for me. When i tried
for data in self.request.data :
print data['image']
TypeError: string indices must be integers, not str
Please how do i achieve this ?Any help would be appreciated.
Below is my ajax request .
$.ajax({
url: "/user/add_collection",
type: 'POST',
contentType:'application/json',
data: JSON.stringify(arr),
dataType:'json',
success : function(data,status){
console.log("The image upload data returns", data);
console.log("the image upload status is", status);
},
error : function(xhr, ajaxOptions, thrownError){
//$.mobile.loading('hide');
if (xhr.status == 200) {
alert(ajaxOptions);
}
else {
alert(xhr.status);
alert(thrownError);
}
}
});
I am using python running flask framework .
I think you are getting the response as a string (self.request.data).
To treat it as objects, you need to convert it (from string to python representation) first:
elif self.request.method == 'POST' :
parsed_json = json.loads(self.request.data)
for data in parsed_json:
print data['image']
JSON data is received as a string. You need to parse it first.
data = json.loads(self.request.data)