I just updated my django to 1.4. But I am getting the following error when I try to submit my login form:
Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect.
In my settings.py (MIDDLEWARE_CLASSES) I had to remove the following line because its now deprecated:
'django.middleware.csrf.CsrfResponseMiddleware',
And than I started to to get this error.
Some necessary information: Urls.py
url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'registration/login.html'}, name='login')
MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
'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.csrf.CsrfResponseMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
login.html
{% extends "base.html" %}
{% block title %} Login {% endblock %}
{% block content %}
<div id="text">
<table>
<form action="" method="post">
{% csrf_token %}
<tr>
<td><label for="username">Email:</label></td>
<td><input type="text" name="username" value="" id="username"></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" name="password" value="" id="password"></td>
</tr>
<tr>
<td><input type="submit" value="Login" />
{% if next %}
<input type="hidden" name="next" value="{{ next }}" /></td>
{% else %}
<input type="hidden" name="next" value="/" /></td>
{% endif %}
</tr>
</form>
</table>
{% if form.errors %}
<p class="error">User or password incorrect</p>
{% endif %}
</div>
{% endblock %}
Does anyone knows how to solve this problem?
The “Invalid or missing CSRF token” message means that your browser couldn't create a secure cookie, or couldn't access that cookie to authorize your login. This can be caused by ad- or script-blocking plugins, but also by the browser itself if it's not allowed to set cookies.
Django features a percent csrf token percent tag that is used to prevent malicious attacks. When generating the page on the server, it generates a token and ensures that any requests coming back in are cross-checked against this token. The token is not included in the incoming requests; thus they are not executed.
The CSRF token is like an alphanumeric code or random secret value that's peculiar to that particular site. Hence, no other site has the same code. In Django, the token is set by CsrfViewMiddleware in the settings.py file. A hidden form field with a csrfmiddlewaretoken field is present in all outgoing requests.
The code looks fine, Django 1.3 and 1.4 auth.views.login uses RequestContext correctly. Please check:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With