another CSRF question -- and django hitcount

52 views
Skip to first unread message

Eric Abrahamsen

unread,
Dec 6, 2014, 3:10:44 AM12/6/14
to django...@googlegroups.com
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

Eric Abrahamsen

unread,
Dec 6, 2014, 11:30:08 PM12/6/14
to django...@googlegroups.com
Eric Abrahamsen <gir...@gmail.com> writes:

Apologies for the very stupid posting below! I did my homework, and
actually used the JQuery ajax function, like I was supposed to.

Incidentally, I also had the "async" keyword on the <script> tag in the
head that loaded jquery, and that apparently killed the document.ready
function altogether. Learned something new.
Reply all
Reply to author
Forward
0 new messages