【问题标题】:Customize user authentication自定义用户身份验证
【发布时间】:2014-01-24 13:53:09
【问题描述】:

谁能提供更多关于自定义 Django 身份验证系统的信息。好吧,我创建了一个自定义用户,我在其中使用电子邮件作为标识符:

    USERNAME_FIELD = 'email'

我创建了一个自定义身份验证后端,并在设置文件中将身份验证后端更改为这个新后端:

    class Custom_Authentication(ModelBackend):
         def authenticate(self, email=None, password=None):
             try:
                user = self.user_class.objects.get(email=email)
                if user.check_password(password):
                   return user
             except self.user_class.DoesNotExist:
                   return None

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

         @property
         def user_class(self):
             if not hasattr(self, '_user_class'):
                self._user_class = get_model(*settings.AUTH_USER_MODEL.split('.', 2))
                if not self._user_class:
                   raise ImproperlyConfigured('Could not get custom user model')
             return self._user_class

但现在我不知道如何使用他的电子邮件验证自定义用户,我是否使用:

    from django.contrib import auth
    def auth_view(request):
        email = request.POST.get('email', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=email, password=password)

        if user is not None:
           auth.login(request, user)
           return HttpResponseRedirect('/loggedin/')
        else:
           return HttpResponseRedirect('/invalid/') 

我试过了,它似乎无法识别我使用管理界面创建的用户。我还有什么需要改变的吗?

【问题讨论】:

    标签: django python-2.7 django-authentication authentication


    【解决方案1】:

    如果您想进行自定义身份验证,我建议您为此制作一个表单。制作一个包含电子邮件和密码的表单,然后编写 clean 方法来验证两者。

    Try taking a look at this answer as an example.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      • 2022-12-10
      • 2016-10-18
      • 2015-02-24
      • 2016-08-04
      相关资源
      最近更新 更多