javascript - Django: AJAX + CSRF POST gives 403 -
i have simple code make post
call url in django
csrf token included. when paste javascript
code in template within <script>
tags, works fine, move code static file, http 403 response. strange!
here code:
$(document).ready(function() { $(".like-button").click(function(event) { $.ajax({ url: <relative path of url>, type: "post", data: { csrfmiddlewaretoken: "{{ csrf_token }}", // other data items }, success: function(data, textstatus, jqxhr) {}, error: function(jqxhr, textstatus, errorthrown) {} }); // other javascript code toggle button class }); });
here's how include static file in django
template:
{% block javascript %} {% load static %} <script type="text/javascript" src="{% static 'app/app.js' %}"></script> {% endblock %}
the file located in static directory:
app ├── static │ └── app │ └── app.js
and static settings are:
static_url = '/static/' static_root = os.path.join(base_dir, 'static')
note, not have staticfile_dirs
in settings yet. can verify file being loaded , executed, since console.log()
statements work fine. however, http 403 request upon post
.
when use tag directly, django processes templates , replaces csrfmiddlewaretoken: "{{ csrf_token }}"
correct token.
now, when use static file, variable isn't replaced. in order add token should configure ajax calls described django documentation: https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax
function getcookie(name) { var cookievalue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); (var = 0; < cookies.length; i++) { var cookie = jquery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookievalue = decodeuricomponent(cookie.substring(name.length + 1)); break; } } } return cookievalue; } var csrftoken = getcookie('csrftoken'); $.ajaxsetup({ beforesend: function(xhr, settings) { xhr.setrequestheader("x-csrftoken", csrftoken); } });