How to pass an HttpResponse and additional data via Ajax in Django - python

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)
}
...

Related

Pass array data through AJAX and get in python file(views.py)

I want to pass array data in views.py file for that I use AJAX and passing data through AJAX. But there I am not able to get all data in views.py file, some of the data are missing.
display.html
var SelectedID = [];
function getvalues() {
$(':checkbox:checked').each(function (i) {
SelectedID[i] = $(this).val();
console.log("Selected Data", SelectedID[i])
$.ajax({
url: "{% url 'addtoexisting' bid=adduser.id %}",
type: "POST",
dataType: "json",
data:{
SelectedID : SelectedID[i],
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
console.log("Selected Data AJAX", SelectedID)
alert("Successfully sent the Data to Django");
},
error: function (xhr, errmsg, err) {
// alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
});
}
views.py
def display(request):
is_ajax = request.headers.get('x-requested-with') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
SelectedID = request.POST.get('SelectedID')
print(SelectedID)
return render(request, 'display.html',{})
SelectedID[i] = $(this).val(); in this selectedID There are 10 records but in print of views.py there is only 6 records, other data are missing.

Wrong redirection of url in django

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"
)

Passing Dict of Arrays using Ajax and Django

I have a dictionary of arrays that I would like to pass to my Django view.
$.ajax({
url: '/fund_monitor/fund_directory',
type: 'GET',
data:{
filter_dict: filter_dict,
},
success: function (data) {
console.log(filter_dict);
}
});
And in my view I would like to receive this dict:
if request.is_ajax():
filter_dict = request.GET.getlist('filter_dict')
print("Is Ajax", filter_dict)
But "Is Ajax []" gets printed out and just as an example, my filter_dict:
Designated Broker:["BMO"]
Fund Class:["OM"]
Any ideas why a blank array gets passed?
$.ajax({
url: '/fund_monitor/fund_directory',
type: 'GET',
data:JSON.stringify({
filter_dict: filter_dict,
}),
success: function (data) {
console.log(filter_dict);
}
});
if request.is_ajax():
request_data = json.loads(request.GET)
filter_dict = request_data['filter_dict']
print("Is Ajax", filter_dict)

how to return data in a format json?

please help.
a form. when you send it to the next page is loaded by the controller:
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import loader, RequestContext
from reviewsFancy.models import ReviewsFancy
from django.cong import settings
import json
def reviewsFancyCall(request):
if request.method == "POST" and request.is_ajax():
c = ReviewsFancy(
title=request.POST.get("title", ""),
name=request.POST.get("name", ""),
message=request.POST.get("message", ""),
)
c.save()
with open(settings.BASE_DIR + 'qwe.txt', "wb") as f:
f.write(bytes('ok', 'UTF-8'))
data = [['result', 'ok']]
return json.dumps(data)
else:
with open(settings.BASE_DIR + 'qwe.txt', "wb") as f:
f.write(bytes('no', 'UTF-8'))
data = [['result', 'no']]
return json.dumps(data)
as a result everything is working as intended. the data is successfully written to the table. but I would check the returned data as follows:
..................
$.ajax({
url: "/reviewsFancy/call/",
type: 'POST',
dataType: "json",
data: {
"title": title.val(),
"name": name.val(),
"message": message.val(),
},
error: function() {
console.log('err');
alert('error');
},
success: function(data) {
console.log('succ');
console.log(data['result']);
title.val('');
name.val('');
message.val('');
$('.reviews_fancy').toggleClass('hide');
alert('success');
},
...............
but in the console I get the error:
POST http://127.0.0.1:8000/reviewsFancy/call/ 500 (INTERNAL SERVER ERROR) jquery.2.min.js:6
XHR finished loading: "http://127.0.0.1:8000/reviewsFancy/call/". jquery.2.min.js:6
err
Every view in Django must return a HttpResponse object, in your case:
return HttpResponse(json.dumps(data), content_type='application/json')
I would also suggest returning a dictionary rather than a list as your response:
data = {'result': 'ok'}

django/python reading json?

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

Categories

Resources