Django views.py is not rendering html file? - python

i am sending an object to backend (django) via ajax "POST" method. in the views.py the code runs but the render statement is not executing.
ajax
$.ajax({
url: '{% url "chout" %}',
data: {
'object': object1,
'csrfmiddlewaretoken':csrf
},
method: "POST",
dataType: 'json',
success: function (data) {
alert("success");
}
});
views.py
return render(request, "mart/checkout.html", {"total": total_price, "final_bill": final_dict})
Everything above return statement runs smoothly but somehow the return line dont run. it is not showing any error or warning either and alert is not popping either.

If the alert is popping up on screen then the return line is running. Use
alert(data);
To see if the html is in there. The window is not going to apply the HTML all on its own.

For using Ajax in django, json response must be returned not the html file

Related

Django view not getting ajax request

I have a script in my template that tries to send data to a django view during onbuttonclick event. My problem is that the request doesn't seem to make it to the view. The browser console sees the request properly and all, but the django view does't even return true when i call request.is_ajax().
request.method returns GET instead of POST, and the data is empty. This behavior is persistent regardless of the request type.
html
<a onclick="setGetParameter(this)" pid="some_id">Some Text</a>
.js
<script>
var csrftoken = Cookies.get('csrftoken');
function setGetParameter(el){
var stuff = $(el).attr('pid');
$.ajax({
type: 'POST',
headers: { "X-CSRFToken": csrftoken },
url: '/view_url/',
data: {'datatopass': stuff},
success: function(response){
alert(response);
}
});
}
</script>
urls.py
path('view_url/', views.test),
path('', views.home),
views.py
def test(request):
output = request.is_ajax()
return HttpResponse(output)
In Django 3.1 is_ajax() method is deprecated. See Miscellaneous Django 3.1
So for Django >= 3.1 you can do it like that:
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
is_ajax = True
else:
is_ajax = False
And make sure that the following line added in AJAX request headers:
"X-Requested-With": "XMLHttpRequest"
I would be use jQuery click method:
<a pid="some_id">Some Text</a>
<script>
var csrftoken = Cookies.get('csrftoken');
function setGetParameter(el){
var stuff = $(el).attr('pid');
$.ajax({
type: 'POST',
headers: { "X-CSRFToken": csrftoken },
url: '/view_url/',
data: {'datatopass': stuff},
success: function(response){
alert(response);
}
});
}
$(document).ready(function(){
$('a[pid]').click(function(){
setGetParameter(this);
});
});
</script>
Also I would be use JsonResponse objects:
from django.http import JsonResponse
def test(request):
output = request.is_ajax()
return JsonResponse({'is_ajax': output})
In order to serialize objects other than dict you must set the safe parameter to False:
response = JsonResponse([1, 2, 3], safe=False)
After days of beating my head against a wall, I chose to go with a different implementation. It appears I can only render the data on the page that initially sent the request.

Failed to load resource: the server responded with a status of 403 (Forbidden)?

i am posting javascript localstorage object to backend(django). I am passing it through ajax.
this is the code in frontend.
function checkout_(){
console.log("checkout");
for(v in list1){
object=Object.values(localStorage)[v];
object = JSON.parse(object)
}
//ajax here
console.log(object.length);
$.ajax({
url: '{% url "chout" %}',
data: {
'object': object
},
method: "POST",
dataType: 'json',
success: function (data) {
alert("success");
}
});
i have given this function to a button via onclick.
<button class="bg-danger text-white " onclick="checkout_()">Go To Checkout Counter</button>
when i click on this button this error "Failed to load resource: the server responded with a status of 403 (Forbidden)" happens.
in the views.py this is the code.
views.py
def checkoutnow(request):
return render(request, "mart/checkout.html")
I hope this detail is enough to explain the problem..Thankyou
You have to pass csrfmiddlewaretoken also in the post call because of csrf middleware set in the settings
const csrf = "{{ csrf_token }}";
and add this key, value pair to your data:
data: {'csrfmiddlewaretoken':csrf, 'object': object },
You can skip this and just use GET instead of POST if feasible.

Ajax call is not going to view function django

Hi I am sending request to a django view but its not accessing view function . Both are in same app . And I am using debugging tool so I tried to debug but on my view no call is received and
My ajax call code is like this
$.ajax({
url: '/edit_profile/',
type: 'get', // This is the default though, you don't actually need to always mention it
success: function(data) {
alert(data);
},
failure: function(data) {
alert('Got an error dude');
}
});
url.py
path('edit_profile/', views.edit_profile , name="edit_profile"),
view.py
def edit_profile(request):
print(request)
print(request)
if request.method == 'POST':
return render(request, 'authenticate/edit_profile.html', context)
I am debugging but call is not received in this view function .
You can see live demo here REPL
First do this if you don't want that your view check the csrf token. This can be done by using decorator #csrf_exempt.
view.py
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def edit_profile(request):
print(request)
if request.method == 'GET':
return render(request, 'authenticate/edit_profile.html')
url.py
path('edit_profile/', views.edit_profile , name="edit_profile"),
ajax request
$.ajax({
url: '/edit_profile/',
type: 'GET',// This is the default though, you don't actually need to always mention it
data:{},
success: function(data) {
alert(data);
},
failure: function(data) {
alert('Got an error dude');
}
});

Flask request returns None; but Ajax Post is successful

In flask I'm using a GET request to first render a template and get data the user has selected.
#app.route('/surveys', methods=['POST', 'GET'])
def register_form():
if request.method == 'GET':
return render_template('survey_table.html')
else:
example = request.json
return json.dumps(example)
This data (which is the #ids of checkboxes selected in a table) is then posted back to FLASK using an ajax Post request. Since the data was initially an array I have used JSON.stringify
$(document).ready(function() {
$('#submit').click(function() {
var list = [];
var checkBoxes = $('#surveyDetails').find("input[type='checkbox']:checked");
checkBoxes.each(function() {
var currentRow = this.parentNode.parentNode;
list.push(currentRow.getElementsByTagName("td")[0].innerText);
});
// now names contains all of the names of checked checkboxes
$.ajax({
contentType: "application/json",
url: '/surveys',
type: 'POST',
data: JSON.stringify({'Hello': list}),
success: function (result) {
alert(result);
},
error: function (result) {
alert("error!");
}
}); //end ajax
});
});
The Problem:
I can see that the ajax post is executed successfully since I am able to see the selected ids as an alert once I click the submit button. However, in flask when I return this JSON object, I always get a null response.
I have already tried get_json(force=True). Still the same result.

django POST returning Internal Server 500 error

I am trying to POST a request to a django view but it keeps returning INTERNAL SERVER ERROR 500.
My ajax post:
$.ajax({
url : "/loginAction/",
type : "POST",
async : false,
data : {action:'loginAction',
email:email,
password:password},
success : function(response) {
$.niftyNoty({
type:"success",icon:"",title:"Login Successful. Redirecting....",container:"floating",timer:5000
});
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
$.niftyNoty({
type:"danger",icon:"",title:"Wrong Email OR Password",container:"floating",timer:5000
});
}
});
My django view:
def loginAction(request):
print "Its workjing"
if request.method == 'POST' and 'loginButton' in request.POST:
email = request.POST.get('email')
password = request.POST.get('password')
print email, password
return HttpResponse(json.dumps({}),content_type="application/json")
My urls.py
urlpatterns = [
url(r'^', views.loginPage, name='loginPage'),
url(r'^loginAction/', views.loginAction, name='loginAction')
]
The ajax POST is not hitting the django view. It is not printing Its working in console. So its not returning the json response to ajax call. I also tried normal form POST but same result. I am using django 1.9.2. I cant figure out why this error?
It returns this error code:
Internal Server Error: /loginAction/
Traceback (most recent call last):
File "/home/manish/Desktop/admin_picknbox/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 158, in get_response
% (callback.__module__, view_name))
ValueError: The view login_app.views.loginPage didn't return an HttpResponse object. It returned None instead.
EDIT:
ajax Header:
jQuery(document).ready(function($){
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
It seems your urls are the problem because in the error appears that the loginPage view is called although you go to /loginAction/. So try to add $ at the end of each regex as below:
urlpatterns = [
url(r'^$', views.loginPage, name='loginPage'),
url(r'^loginAction/$', views.loginAction, name='loginAction')
]
Because it appears that your first regex r'^' captures any url.
Your view function doesn't take care of all cases, in case if request.method == 'POST' and 'loginButton' in request.POST: is False, you view function doesn't return anything, hence the error. Python function, if left without explicit return statement, would return None.
Edit:
If your print statement is not even executed, then you must have 403 response from django. You need to pass csrf token when you make ajax call to prevent attack from unknown person. Django would check csrf automatically, but you need to pass it as part of the data:
data : {action:'loginAction',
email:email,
password:password,
csrfmiddlewaretoken: '{{ csrf_token }}'},
Also, you should check "action" in request.POST not "loginAction" in request.POST.
i got this error one day but i latter realize that the page returning internal server error has the same name as the html page i wanted to return. i just changed the name of the html page i wanted t return and everything worked fine

Categories