1

I have a Django view, named vote. It is protected by a @login_required decorator, and in normal use works completely fine.

I decided it would be a worthwhile idea to start looking into ajax and javascript to make the system more dynamic, and so I implemented something like the below for my first try:

$(function() {
        $(".vote").click(vote);
});

var vote = function() {
            pk = $(this).attr('pk');

            $.ajax({
                type: "POST",
                data: "pk=" + $(this).attr("pk"),
                url: "/link/" + $(this).attr("pk") + "/vote/",
                });
        };

Which successfully POSTS to the correct URL. When I look at the output with firebug, I find I'm getting 500 errors. I've included the snipped from https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax into my pages, which I had thought would solve the CSRF issue, however it appears not to have done so.

Wondering whether I'm missing something obvious!

Thanks!

jvc26
  • 6,363
  • 6
  • 46
  • 75

1 Answers1

0

Turns out the way that I solved this was to tidy up the above:

var vote = function() {
        pk = $(this).attr('pk');

        data = {
            'pk': pk
        };

        $.ajax({
            type: "POST",
            data: data,
            url: "/link/" + pk + "/vote/",
            });
    };

Thus tidied, I then checked out the view, and discovered that it was not pulling the correct value out of the DataDict passed to it by ajax, which was where the 500 error was coming from.

I had previously encountered a 403 due to the CSRF issue, for those wondering how to solve that, I simply used the script mentioned in the question above, saved in a 'csrf.js' file in the /static/js/ directory of my app, and then included that as one of the scripts, which then solved that issue.

jvc26
  • 6,363
  • 6
  • 46
  • 75