Moving from 1.2 to 1.6

74 views
Skip to first unread message

John Fabiani

unread,
Apr 9, 2014, 1:47:12 PM4/9/14
to django...@googlegroups.com
Hi,

I be honest this {% csrf_token %} has me completely baffled.  I have read the doc's and I guess I have to admit I don't understand what I'm doing.

I have
<form  id="registration_form" method="post" action="/register/registeruser/" >
{% csrf_token %} ...
Which I think is the correct way to add the token.

My form uses
submitHandler : function(form){$(form).ajaxSubmit({ beforeSubmit : showRequest, success: showResponse, dataType : "json"});}

The submit button does this:
function showRequest(formData, jqForm, options){
        var csrftoken = $.cookie('csrftoken');

But I still get a 403 error.  I need some help.

below is the entire code for the view.
https://dpaste.de/JOZE


Thanks is advance,
Johnf

C. Kirby

unread,
Apr 9, 2014, 1:51:18 PM4/9/14
to django...@googlegroups.com, jo...@jfcomputer.com
Hi John,
You are mostly there, but you are missing necessary headers on the ajax request.
It isn't that much code. Just follow the couple of paragraphs of doc and examples here: https://docs.djangoproject.com/en/1.6/ref/contrib/csrf/#ajax

Kirby

John Fabiani

unread,
Apr 9, 2014, 2:54:38 PM4/9/14
to C. Kirby, django...@googlegroups.com
I've read that paragraph 15 different ways (maybe even standing on my head).  I still don't understand what I'm missing.
Believe me I realize I might be the only person that doesn't get it - such is life.

Could you highlight what exactly I'm missing.  What do you mean by "missing necessary headers"?

The code that includes the 'headers' in the doc's is exactly the part I don't understand.  Where does that code go and how does it relate to my code.

Johnf

John Fabiani

unread,
Apr 9, 2014, 2:57:24 PM4/9/14
to django...@googlegroups.com
Also I was using jquery 1.4 with Django 1.2.  Should I upgrade the jquery?

Johnf
--
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...@googlegroups.com.
To post to this group, send email to django...@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/5345976E.7090406%40jfcomputer.com.
For more options, visit https://groups.google.com/d/optout.

C. Kirby

unread,
Apr 9, 2014, 3:22:52 PM4/9/14
to django...@googlegroups.com, jo...@jfcomputer.com
Okay. I may get a few of the details wrong here, but the general idea should be correct.
Basically CSRF makes sure that the request is coming from a page served by the same domain. In order to do this it checks the REFERRER header to make sure it is in the same domain. The cookie that you grab using the code you showed is used in generating the ajax headers.

So, how to use it. I do it slightly differently than the example - I use jquery .ajaxSend() instead of the $.ajaxSetup() they provide. What I like about the way I use it is you put all of the ajax related csrf code in one $(document) block in an always included .js file and it Just Works(TM)

Here is the code that I use:

$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

jquery is up to 1.11 (on the 1.x branch) you will probably gain a lot from upgrading, but I would be a bit worried about deprecated features. Try it out, if it works with no issues - great, if not then you can decide if you want to fix the errors or revert.

Kirby

John Fabiani

unread,
Apr 9, 2014, 5:18:02 PM4/9/14
to django...@googlegroups.com
The code looks great.  I just do not know where the code goes and how it is to be called.
For example:  Should the code you provided be in .alaxSubmit -> beforeSubmit: showRequest or is there some other way I should call the functions.  Does the code add to my data - if so where and how does that work?

I tired adding the code to the beforeSubmit but still get the 403 error.  I'm missing something very fundamental.

Johnf

John Fabiani

unread,
Apr 9, 2014, 7:00:34 PM4/9/14
to django...@googlegroups.com
Do you guys think is possible the jQuery Form plugin is some how interfering with the token?

Johnf

Nick Santos

unread,
Apr 9, 2014, 7:25:58 PM4/9/14
to django...@googlegroups.com
Hey John,

Is this a server you could turn set DEBUG=True for and send this list the results of the error page that's produced? That could be super valuable in tracking down the error.

-Nick

John Fabiani

unread,
Apr 9, 2014, 8:59:37 PM4/9/14
to django...@googlegroups.com

I have created a csrf.js added the code.
I added it to the html base
<script type="text/javascript" src="/site_media/js/csrf.js"></script>

I've added the {% csrf_token %} in the form.


Where oh where do I use the code or is it magic!  Does it really work?

I don't mean to be an ass but using google search I find over 20,000 hits on the django and csrf on several of the sites.  Stackoverflow has 12,000 + on one page about this

http://stackoverflow.com/questions/6506897/csrf-token-missing-or-incorrect-while-post-parameter-via-ajax-in-django/6533544#6533544

This might be the greatest thing since slice bread but I can't figure out how to use it!

At this point I'm willing to pay some guru!

And below is what I get from debug.

Reason given for failure:

    CSRF cookie not set.
    

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

  • Your browser is accepting cookies.
  • The view function uses RequestContext for the template, instead of Context.
  • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
  • If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.

You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

Johnf

Nick Santos

unread,
Apr 9, 2014, 9:13:42 PM4/9/14
to django...@googlegroups.com, jo...@jfcomputer.com
Thanks for that. If you inspect a generated page with the form using something like Firebug or Chrome Inspector, can you confirm that there is a hidden form element named csrfmiddlewaretoken? If you're trying to serialize the values in the page to send via AJAX, you can try using that value instead of the cookie value (I've AJAXed many forms and have never dealt with a CSRF cookie).

Also, does the form work if you don't send it via AJAX and just do a normal POST/GET from the browser?
-Nick

John Fabiani

unread,
Apr 9, 2014, 9:58:47 PM4/9/14
to django...@googlegroups.com
If I turn off the csrf with @csrf_exempt the form works.  I'm sort of a newbie so the only django code I used was as posted.  I just installed the jQuery form plugin and it worked as suggested.  So the code I posted is the only code I have ever coded.  I do believe I understand python at a higher level but as far as javascript I'm really a newbie.

Johnf
Reply all
Reply to author
Forward
0 new messages