用户无法进行身份验证

时间:2018-04-21 18:53:18

标签: python django

我正在使用自定义用户模型进行自定义身份验证。

当用户进行身份验证时,根据需要重定向到主页,但用户未通过身份验证。 当我签入模板{{user.is_authenticated}}时,它会显示为False。

如何解决这个问题?

这是我的自定义身份验证的后端文件:

from contracts.models import User
from django.contrib.auth.hashers import check_password

class AuthBackend:
    def authenticate(self, email=None, password=None):
        try:
            user = User.objects.get(email=email)
            if not check_password(password, user.password):
                return None
        except User.DoesNotExist:
            return None
        return user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

我的观点:

class LoginView(View):
    form_class = LoginForm
    template_name = 'login.html'

    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():

            email = form.cleaned_data['email']
            password = form.cleaned_data['password']

            user = authenticate(email=email, password=password)

            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('/')
        return render(request, self.template_name, {'form': form})

已添加到我的设置文件中:

AUTHENTICATION_BACKENDS = ['contracts.auth.backend.AuthBackend']
AUTH_USER_MODEL = 'contracts.User'

Django版本为2.0.4

1 个答案:

答案 0 :(得分:0)

我在更改login导入时修复了它:

from django.contrib.auth.views import login

为:

from django.contrib.auth import login