I\'m getting many failures from the CSRF Django middleware on my site (the version from SVN trunk.) The only errors I get are: CSRF failure: reason=CSRF token missing or incorr
I really struggled to get it right, but eventually did. Here were my main issues (Django 1.2 beta):
Make sure that your settings emails are all the right ones. I had to do something like this:
EMAIL_HOST='mail.my-domain.com' EMAIL_HOST_USER='my user name on the server' EMAIL_HOST_PASSWORD='passwd' EMAIL_PORT= '26' # often seems to be 25 or 26 on many of the forum posts I read DEFAULT_FROM_EMAIL='noreply@domain.com' # on hosted domains, make sure it is set up and sending SERVER_EMAIL = 'noreply@domain.com' # Same email as above
return render_to_response('contact.htm',{'favicon':r'____.ico', 'more_stuff':"......" 'more_stuff':"......" 'more_stuff':"......" }, context_instance = RequestContext(request))
Make sure you have:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.csrf",
.....
)
in your settings.py file.
Note that this is really not a how to, this is just what I did to get mine working. The reason for posting it now is that I see so many people on forums discussing this topic resort to just turning the csrf_token off.
Make sure your view function for GET Request looks like this:
def login_view():
c = {}
c.update(csrf(request))
request.session.set_expiry(0)
if request.method == 'GET':
return render_to_response('newform.html',<b>c</b>)
Then check the view source for your newform.html, it must have Hidden field.
<`form action="" method="post" name="loginform"> <`div style='display:none'`><`input type='hidden' name='csrfmiddlewaretoken' value='6f4dee99ab2f5e7201e057cb63' />
Here, action can refer the same page, action=""
.
Also you should check the order of the MIDDLEWARE_CLASSES
in your settings.py
file. Should look something like this:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
)
LocaleMiddleware
at the end.
For me, the solution was the RequestContext
instance and the ordering.
A CSRF error should happen when the middleware successfully stops a Cross Site Request Forgery attack. Probably the best way to verify that this is the case it to check your web server logs and you should see requests that aren't related to an earlier request.