Keep in mind whenever you are using CSRF, you need to pass an instance of RequestContext back to the view. In addition, your form needs to have {% csrf_token %} added to it.
In your view code, you can use the render shortcut which will incude the correct context for you:
from django.shortcuts import render
def admin_login(request):
# your normal code
return render(request, 'admin/login.html', {'username': username})
The CSRF section of the documentation has a checklist of what is required in order for CSRF to work correctly.
You should also use authenticate() instead of writing your own logic:
from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
Putting all that together, your code is now:
from django.shortcuts import render
from django.contrib.auth import authenticate
from django.contrib import messages
def admin_login(request):
"""Logs in an admin user, redirecting to the dashboard"""
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username, password)
if user is not None:
if user.is_active:
login(request, user)
request.session['admin_id'] = user.id
return redirect('dashboard')
else:
# do something because user was not active
messages.add_message(request, messages.ERROR, 'User Inactive')
return render(request, 'admin/login.html')
else:
# password/username combination was wrong
messages.add_message(request, messages.ERROR, 'Invalid Credentials')
return render(request, 'admin/login.html')
else:
return render(request, 'admin/login.html')
I am using the built-in messages framework to display the error messages.