views:

61

answers:

1

Hi All,

I have a GWT web app working with Django server-side. I recently upgraded Django to 1.2, and am not able to get HTTP posts to work from my GWT app. I am getting this error:

CSRF verification failed. Request aborted.

Reason given for failure:

CSRF token missing or incorrect.

I have enabled the csrf middlewares ('django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.csrf.CsrfResponseMiddleware') which is working for contrib apps like login, but it seems as though the token is not getting added to posts made through GWT. Any ideas? Thanks in advance.

A: 

If you have checked the templates for auth.login you'll notice that a CSRF token is explicitly included inside the <form> tag.

<form method="post" action=".">
    {% csrf_token %}

This is expanded into a hidden field when the page is rendered on a GET request. Something like:

<form method="post" action=".">
    <div style='display:none'>
        <input type='hidden' name='csrfmiddlewaretoken' 
             value='90064bf0e86edacfdb60595e3e2b8f23' />
    </div>

This token is then passed back to the view on POST and validated.

Consequently before you can POST to a CSRF protected view you will have to first get the token from the said view.

Can you verify/ensure that you have the CSRF token handy before making a POST request to the view? Alternately you can disable CSRF protection for the view using the csrf_exempt decorator. This may not be a good idea though.

Update

This is the point of my question: I am not using django templates for my front-end and thus I cannot tag forms with the token. I am using GWT for my front-end, which is rendering the form for the post.

Are you already making a GET request to the Django view before rendering the page? In that case you can get the CSRF token by parsing the contents of the response.

If not you will have to explicitly make a GET request to the view (assuming it supports GET) and parse the response for a CSRF token. For an example see this question.

Manoj Govindan
This is the point of my question: I am *not* using django templates for my front-end and thus I cannot tag forms with the token. I am using GWT for my front-end, which is rendering the form for the post.
NP
@NP: updated my answer. See above.
Manoj Govindan