I have a question about the django-hitcount app that I think is likely
csrf-related.
I recently upgraded a site from Django 1.4 all the way to 1.7. I've got
most everything working fine, except that the hitcount app I've been
using[1], stopped recording hits.
Nevermind the actual app, it works by making an ajax call to a certain
URL when a page is opened. Right now, the rendered javascript looks like
this:
<script type="text/javascript"><!--
$(document).ready(function() {
$.post( '/ajax/hit/',
{ hitcount_pk : '1767', csrfmiddlewaretoken: csrf_token },
function(data, status) {
if (data.status == 'error') {
// do something for error?
}
},
'json');
});
--></script>
Since I upgraded, no hits have been recorded. I can't say for sure it's
csrf-related, but I've been looking at the docs[2], and suspect that's
the problem.
The string "csrf_token" is produced as a hardcoded string, not a
variable or anything -- that seems awfully wrong to me.
After looking at the docs, and installing the cookie plugin, and
scratching my head, this is what I've come up with:
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$(document).ready(function() {
$.post( '/ajax/hit/',
{ hitcount_pk : '{{ object.pk }}'},
function(data, status) {
if (data.status == 'error') {
// do something for error?
}
},
'json');
});
("object" is the variable )
Does this seem right? Will the ajaxSetup apply to my post, even though I
haven't said anything explicitly to that effect?
I apologize for such a brainless set of questions -- I don't know JS
very well, and don't know how to debug it. How could I even tell if this
was working?
Eric
[1]: https://github.com/scottwrobinson/django-hitcount/
[2]: https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/87oarh5h57.fsf%40gmail.com.
For more options, visit https://groups.google.com/d/optout.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment