1

I extends AbstractBaseUser and I try to write login function but i got this error:

CSRF verification failed. Request aborted.

in views.py

def admin_login(request):
username = password = ''
if request.POST:
    request.session.delete_test_cookie()
    username = request.POST.get('username')
    password = request.POST.get('password')
    admin = Administrator.objects.all.get(username__exact=username)
    if admin is not None and admin.check_password(password):
        login(request, admin)
        request.session['admin_id'] = admin.id
        return redirect('dashborad')
return render_to_response('admin/login.html',{ 'username': username})
Amir Asaad
  • 88
  • 1
  • 9

1 Answers1

5

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.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284