I'm using this tutorial to try out creating a django login application (super simple stuff...)
This is the code I end up with in my template (index.html
)
<div id="login-box">
{{ state }}
<form class="login-widgets" action="/login/" method="post">
{% if next %}
<input class="login-widgets-text" type="hidden" name="next" value="{{ next }}" />
{% endif %}
Username :
<input class="login-widgets-text" type="text" name="username" value="{{ username}}" /><br />
Password :
<input type="password" name="password" value="" /><br />
<input class="login-button" type="submit" value="Log In" />
</form>
<!--<div class="login-widgets">
<p>Username : ___________</p>
<p>Password : ___________</p>
</div>-->
</div>
And this is what the tutorial told me to add to my app views.py
page:
def login_user(request):
state = "Please log in below..."
username = password = ''
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
state = "You're successfully logged in!"
else:
state = "Your account is not active, please contact the site admin."
else:
state = "Your username and/or password were incorrect."
return render_to_response('index.html',{'state':state, 'username': username})
I set up my test database exactly as it was described in the tutorial and on the django docs, but still my login keeps getting this error in the browser:
Forbidden (403)
CSRF verification failed. Request aborted.
I don't understand what it means by CSRF verification - in my settings.py
I have set up the MIDDLEWARE_CLASSES with the following:
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', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', )
But I'm not sure how to verify the CSRF and authenticate login. As far as I know, the database super user and the code above looks correct, except I don't know how to add CSRF verification. Thank you so much for your help!
Add {% csrf_token %}
inside your form. It will be replaced by a hidden input with a key.
Step by step documentation.
Concept explanation.