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');
}
});
Related
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.
I made this API permission
def has_permission(self, request, view):
return request.user.is_authenticated and (
request.user.is_superuser or
models.AllowedToUseAPIList.objects.filter(user=request.user).exists()
)
where I check if user who asks for API is added into list of AllowedToUseAPIList.
But I also need to make AJAX requests from other pages of this website to this API. How can I change the permission to allow doing that?
I also pass my CSRF token into AJAX call but get 403.
I make Ajax call like that:
let csrf = $("input[name='csrfmiddlewaretoken']").val();
...
$.ajax({
url:"{% url 'api:ajax_api:save-mark' %}",
method: 'POST',
data:{
"csrfmiddlewaretoken": csrf,
"name": that.name,
"value": value,
},
success: function (data){
...
}
})
After all, I get 403 Permission Denied.
Try adding a parameter that tells the view when a bypass is allowed:
js:
$.ajax({
url:"{% url 'api:ajax_api:save-mark' %}",
method: 'POST',
data:{
"csrfmiddlewaretoken": csrf,
"name": that.name,
"value": value,
"bypass" : true, // add this parameter
},
success: function (data){
...
}
})
python:
def has_permission(self, request, view):
# check if request was triggered by ajax:
ajax_bypass = 'bypass' in request.POST and request.POST['bypass']
# check if use is a superuser:
user_is_superuser = request.user.is_superuser
# check if user is in allowed list:
user_is_authorized = models.AllowedToUseAPIList.objects.filter(user=request.user).exists()
return ajax_bypass or user_is_superuser or user_is_authorized
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
Ajax method to post and passing a string to the views.py, the post method in the views.py can receive values from ajax but I cannot get the results value to print back in the ajax success method.
I have tried to return HTTPresponse, redirect, render but nothing seem to work for me.
//Ajax//
$("#viewData").click(function(event){
$.ajax({
type: "POST",
data: {
tempData : "permView",
csrfmiddlewaretoken: '{{ csrf_token }}',
},
success: function(result) {
console.log('{{ result }}')
},
});
event.preventDefault()
});
});
//Python//views.py
class SpreadSheetView(TemplateView):
template_name = 'spreadsheet.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name, {'type': '86'})
def post(self, request):
if request.POST['tempData'] == 'permView':
return render(request, self.template_name, {'result': "test result"})
You are encountering one of these two problems:
You might be getting an error in your view and cannot notice it since you do not cover error case in your ajax request. Just update your ajax request call like this and see if you are getting an error.
You are not specifying dataType parameterto your request, which causes ajax to incorrectly guess your response type.
To cover these two items, update your request such as:
$.ajax({
type: "GET",
dataType : 'html', # or other types, depending on your needs.
data: {
tempData : "permView",
csrfmiddlewaretoken: '{{ csrf_token }}',
},
success: function(data, status) {
console.log(data)
console.log(status)
},
error: function(xhr, status, error) {
console.log(status);
console.log(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