Ajax error in Django

I have the following ajax call to update a specific model field

$("#updateLink").click(function(){ var dec_text = $('#desc_text').val(); $.ajax({ type: "POST", url:"/users/update_desc/", data: { 'val': dec_text, }, success: function(){ $(".display, .edit").toggle(); $("#descText").html(dec_text); }, error: function(){ alert("Error"); }, }); return false; }); 

and my look at that

 @csrf_exempt def update_desc(request): if request.is_ajax(): if request.method == 'POST': desc_text = request.POST.get('val', False) if desc_text: profile = user.profile profile.desc = desc_text profile.save() return_message = "Sent mail" return HttpResponse(return_message,mimetype='application/javascript') 

I keep getting an error and I don’t know how to solve it. I even used the csrf_exempt decorator to work around if the problem was caused by a missing csrf token , but the problem still persists.

With the exception of one ajax post , which in my base template does not work all ajax calls. Someone can help to understand what is happening here. If necessary, I can provide more detailed information.

Edit:

I added a js file containing this https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax in my base template, so that means that it is present in all of my templates. And I am using django version 1.3.

+6
source share
1 answer

First, you use POST and do not send the csrf token. Try explicitly sending the csrf token instead of using the csrf_exempt decorator.
One way to do this is what I did in the data. That is, to get the csrf token (or from your own method) and pass it to your arguments.

 $.ajax({ url : url, type: "POST", data : {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value}, dataType : "json", success: function( data ){ // do something } }); 
+6
source

Source: https://habr.com/ru/post/904735/


All Articles