13👍
Another option would be to adapt the cookie/header based solution shown in the Django docs with Ext – preferable if you have a lot of templates and don’t want to change every single one.
Just drop the following snippet in your overrides.js (or wherever you put global modifications):
Ext.Ajax.on('beforerequest', function (conn, options) {
if (!(/^http:.*/.test(options.url) || /^https:.*/.test(options.url))) {
if (typeof(options.headers) == "undefined") {
options.headers = {'X-CSRFToken': Ext.util.Cookies.get('csrftoken')};
} else {
options.headers.extend({'X-CSRFToken': Ext.util.Cookies.get('csrftoken')});
}
}
}, this);
(edit: Ext already has cookie reading function, no need to duplicate it)
9👍
The easiest way is to create a hidden form on your page using django that doesn’t do anything. Then use JavaScript to fetch the form and specifically the token input out of the form. Lastly, insert or copy that token input into the form you are dynamically generating.
Here are two examples of how you might publish the token for JavaScript.
<input id="csrf_token" value="{{ csrf_token }}"/>
<script type="text/javascript">
var CSRF_TOKEN = document.getElementById('csrf_token').value;
</script>
or
<script type="text/javascript">
var CSRF_TOKEN = "{{ csrf_token }}";
</script>
1👍
A better solution is to generate the code of the js file from a view/template.
Then, in the view you can set the csrf token up in the context like so…
from django.core.context_processors import csrf
context = RequestContext(request)
context.update(csrf(request))
Then, in the template, you can use {{ csrf_token }}
to get the raw value of the csrf token, and then use that to build a hidden field into your form with the name csrfmiddlewaretoken
.
- How to have Accent-insensitive filter in django with postgres?
- Timeout when uploading a large file?
- Django + uwsgi + nginx + SSL
- Saving Base64ImageField Type using Django Rest saves it as Raw image. How do I convert it to a normal image
0👍
Does the view you are POST
ing to also respond to GET
? In that the JS code can make a GET
request to the view in question and parse the output to extract the CSRF token. My JS-fu is weak and I am not sure how best you can do the parsing from the client side.
For a broadly related example see this question. In this case the user was attempting to POST
using a Python script and failing for the same reason. The solution was the same, except he had to do it from a Python script rather than JavaScript.
- Django conditional Subquery aggregate
- Python – pyodbc call stored procedure with parameter name
- Readonly fields in django formset
0👍
This may not be ideal, but it was the fastest solution for me. In my main template at the bottom of the “body”, I added a javascript function to my library.
<script type="text/javascript">
MyToolkit.Utils.getCSRFToken = function () {
return "{% csrf_token %}";
};
</script>
- Django Deployment: Handling data in database
- Django AttributeError: 'Alias' object has no attribute 'urls'
- Django-registration – how do i change example.com in the email?
- Django REST Framework and generic relations
0👍
This will use the csrf token or auto generate a new one if needed. It will handle all form submits on the page. If you have off-site forms you’ll need to make sure they don’t run this code.
<script>
$(document).on('submit', 'form[method=post]', function(){
if(!document.cookie.match('csrftoken=([a-zA-Z0-9]{32})')) {
for(var c = ''; c.length < 32;) c += 'abcdefghijklmnopqrstuvwxyz'.charAt(Math.random() * 26)
document.cookie = 'csrftoken=' + c + '; path=/'
}
if(!this.csrfmiddlewaretoken) $(this).append('<input type="hidden" name="csrfmiddlewaretoken">')
$(this.csrfmiddlewaretoken).val(document.cookie.match('csrftoken=([a-zA-Z0-9]{32})')[1])
})
</script>
requires jQuery 1.7+