3👍
You can include the csrf token in the data your posting.
You can either extract it from the hidden field in the html form:
<input type="hidden" name="csrfmiddlewaretoken" value="IxwFarTrerVBZbVDX0elVHUEbh0YH58j">
using a jquery selector:
var token = $('input[name="csrfmiddlewaretoken"]').val();
Or if you prefer plain js as you have mentioned you can use this function to extract it from the document cookies:
function getCookie(name) {
var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
var token = getCookie('csrftoken');
👤fips
1👍
I think a simpler approach would be to use cookies. A csrf token is just a cookie whose value you can retrieve. Kindly look at the section on Ajax
and see if it can offer any help https://docs.djangoproject.com/en/1.9/ref/csrf/#ajax.
var csrftoken = Cookies.get('csrftoken');
Doing that using the javascript cookie library should ideally help you to retrieve the csrf token.
- [Django]-How to combine select_related() and value()?
- [Django]-Can a django app have more than one views.py?
- [Django]-Error:Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name
Source:stackexchange.com