DJANGO POST GET not working after i18n translation - django

I have multiple POST requests from my template for example:
$.ajax({
url: '/apply_payment',
type: 'POST',
data: {
basket: JSON.stringify(basket),
key: $('#key_input').val(),
csrfmiddlewaretoken: CSRF_TOKEN
},
dataType: 'json',
success: function (data) {
$("#key_input").val("");
},
...
I read in the basket data in a view.py like this:
basket = request.POST.get('basket', '')
In the urls.py I have these urls in the form of:
path('apply_payment', entrance_api.apply_payment, name='apply_payment'),
Now lately I added i18n_patterns into the URLs, and translated all of my pages, however the AJAX calls stopped working. I guess it is becase the URLs are dynamically changing between selected languages, but I might be wrong.
For example the shows basket variable is always None in the view now. How can I fix this?

From my experience, I had to prepend a language code to the POST request URL:
$.ajax({
url: '/en/apply_payment', // prepend a language code or even better: use window.location.href
type: 'POST',
data: {
basket: JSON.stringify(basket),
key: $('#key_input').val(),
csrfmiddlewaretoken: CSRF_TOKEN
},
dataType: 'json',
success: function (data) {
$("#key_input").val("");
},

Related

CSRF token missing - django/ajax

CSRF token missing - django/ajax
Have already tried each and every solution proposed in this article but nothing seems to work for me.
"CSRF token missing or incorrect" while post parameter via AJAX in Django
$(document).on('click', '.attendance_submit', function(){
var urlname = '{% url "test" %}'
var tableSel = $('.attendance_table tr:not(.group)');
alert("DATA :"+html2json(tableSel));
$.ajax({
url : urlname,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: {
csrfmiddlewaretoken: '{% csrf_token %}',
'TableData': html2json(tableSel)
},
success:
alert('Attendance updated successfully')
});
return false;
});
PS:
CSRF Token is also enabled in the form which I am using in this template, even tried removing from the form but to no avail.
I was finally able to solve this problem using the below code
#SeriForte 's answer pointed me in the right way when I was trying to troubleshoot some other issue.
{ "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" }
$(document).on('click', '.attendance_submit', function(){
var urlname = $(this).attr('data-url');
var tableSel = $('.attendance_table tr:not(.group)');
const csrftoken =
document.querySelector('[name=csrfmiddlewaretoken]').value;
alert("DATA :"+html2json(tableSel));
$.ajax({
url : urlname,
method: 'POST',
headers:{
contentType: 'application/json',
'X-CSRFToken': csrftoken
},
body: JSON.stringify(html2json(tableSel)),
success:
alert('Attendance updated successfully')
});
return false;
});

Django - 403 (Forbidden): CSRF token missing or incorrect with Ajax call. Tried everything

I know this is a well worn question and I scoured the web and this website finding countless answers that boil down to the very same solutions and none of them worked for me and I do not know why. my info/trials so far:
suprisingly the csrf_exempt decorator does not work
tried setting up Headers/beforeSend once before all Ajax calls, it does not work (I tried setting the headers both in call and just once for all the ajax calls)
I can pick up the django token easily both via javascript or via django {{ token }}
django.middleware.csrf.CsrfViewMiddleware is present in the settings.py
python 3.8; django 2.2
[UPDATE] I tried removing contentType to no avail as well
here below you can see the different trials in /*...*/
var csrftoken = '{{ csrf_token }}'
$.ajaxSetup({
crossDomain: false,
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrftoken)
}
});
$.ajax({
url: '/do_things/',
type: 'POST',
contentType: 'application/json',
data: {
/*'csrfmiddlewaretoken': csrftoken*/
},
beforeSend: function (xhr) {
/*xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');*/
/*xhr.setRequestHeader('X-CSRFToken', csrftoken);*/
/*xhr.setRequestHeader('X-CSRF-Token', csrftoken);*/
},
headers: {
/*'X-CSRFToken': csrftoken,*/
/*'X-CSRF-Token': csrftoken*/
},
success: function (data) {
console.log('Fill all the tables')
}
})
on the view side
#login_required(login_url='/login/')
def do_things(request):
if request.method == "POST":
...
on the url side ( in case I messed up something here):
urlpatterns = [
#...
path('r/', views.do_things, name='do_things'),
]
Resources:
a) Forbidden (CSRF token missing or incorrect.) | Django and AJAX
b) Adding CSRFToken to Ajax request
c) https://docs.djangoproject.com/en/2.2/ref/csrf/
let csrftoken = '{{ csrf_token }}'
$.ajax({
type: "POST",
headers:{'X-CSRFToken':csrftoken},
url: "{% url 'Wishlist' %}",
data: {'product_id':product_id},
success: function (response) {
console.log(response, typeof(response))
}
})
I used simple ajax with csrf in the header and it's working fine.
when i use your code in mine, so function calls but data gets blank. i have refered this Django csrf token for Ajax

Coldfusion <cfsavecontent> variable displays correctly on page but does not save correctly to the DB

I have AJAX writing a result to <span id="response"></span>, which displays as expected. But, I need to convert to a CF variable so I can write the content to the database. Using
<cfsavecontent variable="JSONResponse"><span id="response"></span></cfsavecontent>
allows me to display the new JSONResponse variable on the page correctly, but when I take the same varible and write it to the database, it writes the <span id="response"></span> tag into the table - not the actual content. Does anyone have any suggestions? Thanks
Thanks #GSR & #Dan - I managed to work out a solution by forwarding on to a CFM page that writes to the DB, via another nested ajax post, based upon the response:
var postData = {username: "user#company.com", password: "Ruu3992032!883jj22uje"};
var ajaxResponse = $.ajax({
type: "post",
url: "https://api.company.com/v1/authenticate",
contentType: "application/json",
data: JSON.stringify( postData )
})
// When the response comes back, forward on to another cfm page with insert statement.
ajaxResponse.then(
function( apiResponse ){
$.ajax({
type: "post",
url: "WriteToDB.cfm",
data: jQuery.param({ payload: JSON.stringify( apiResponse ) }) ,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
})
}
);

Forbidden (CSRF token missing or incorrect.):

I am making ajax call like below:
var data_dict = {'user':{{ user.id }}, 'bookId':that.id, 'csrfmiddlewaretoken': '{{ csrf_token }}'};
$.ajax({
type: 'POST',
url:"/issuebook",
data:data_dict,
processData: false,
contentType: false,
success:function(response)
{
}
});
urls.py is:
urlpatterns = [
url(r'^$',views.checkLogin,name='checklogin'),
url(r'^mylibrary/(?P<pk>\d+)/(?P<user_name>[\w\-]+)$',login_required(views.MyLibrary.as_view()),name='mylibrary'),
url(r'^centrallibrary/(?P<pk>\d+)/(?P<user_name>[\w\-]+)$',login_required(views.CentralLibrary.as_view()),name='centrallibrary'),
url(r'^issuebook$',login_required(views.IssueBookView.as_view()),name='issuebook'),
]
I am getting "Forbidden (CSRF token missing or incorrect.): /issuebook" error on ajax call.
The csrf token in ajax call is getting rendered as:
var data_dict = {'user':{{ user.id }}, 'bookId':that.id, 'csrfmiddlewaretoken':'fSSdu8dJ4FO6FvDz8eU5ISzOewRYyGbC'};
$.ajax({
type: 'POST',
url:"/issuebook",
data:data_dict,
contentType: false,
success:function(response)
{
}
});
This error is caused by processData and contentType options in your ajax function. Removing these two options will fix the issue.
Explanation:
The arguments must be sent to Django as urlencoded with Content-Type application/x-www-form-urlencoded. Whereas, if you set processData: false it won't encode the POST parmaters and contentType: false will send ajax POST request as text/plain.

Ajax post for django form not working

For some reason I cannot get a successful post when trying to use ajax. The code I am trying is here:
http://jsfiddle.net/MRKNq/11/
$('#register_form').submit(function(e) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: $('#register_form').serialize(),
success: function(data) {
alert(data.text);
$('#result').text(data.text);
},
type: 'POST'
});
e.preventDefault();
});​
Any suggestions would be greatly appreciated.
You should look at the response that comes back in Firebug or some other tool. This likely has to do with CSRF.
Have a look at this: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
You can also exempt your view from CSRF protection by using this decorator: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.csrf_exempt