1

我扩展了 AbstractBaseUser 并尝试编写登录功能,但出现此错误:

CSRF verification failed. Request aborted.

在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})
4

1 回答 1

5

请记住,每当您使用 CSRF 时,您都需要将一个实例传递RequestContext回视图。此外,您的表单需要{% csrf_token %}添加到其中。

在您的视图代码中,您可以使用将为您包含正确上下文的render快捷方式:

from django.shortcuts import render

def admin_login(request):
   # your normal code
   return render(request, 'admin/login.html', {'username': username})

文档的CSRF 部分有一个清单,列出了 CSRF 正常工作所需的内容。

您还应该使用authenticate()而不是编写自己的逻辑:

from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')

将所有这些放在一起,您的代码现在是:

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')

我正在使用内置消息框架来显示错误消息。

于 2013-04-30T09:50:24.677 回答