【问题标题】:can someone give me a hand and example this script? django有人可以帮我看看这个脚本吗? django
【发布时间】:2017-04-22 01:45:16
【问题描述】:

我在网上找到了一个脚本,它可以帮助我将登录更改为同时使用用户名和电子邮件,而不仅仅是用户名,但有很多部分我并不真正理解。

就像,我非常了解每一行的含义,但我不明白为什么这样做会使我的登录与电子邮件一起使用。

class EmailBackend(object):
    def authenticate(self, username=None, password=None):
        user_cls = get_user_model()
        try:
            user = user_cls.objects.get(email=username)
            if user.check_password(password):
                return user
        except user_cls.DoesNotExist:
            return None
        except:
            return None

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

提前致谢。

【问题讨论】:

  • 此脚本使用用户名标题而不是电子邮件,但在后端此用户名必须是电子邮件user = user_cls.objects.get(email=username) 您可以将用户名更改为电子邮件,没关系。

标签: python django login model


【解决方案1】:

检查 cmets :-

class EmailBackend(object):
    def authenticate(self, username=None, password=None):
        user_cls = get_user_model() #Getting user object in one variable

        try:
            user = user_cls.objects.get(email=username) #Check any user exist with input email(username) with database email(consider as an username)
            if user.check_password(password): #if user match then check is password match or not 
                return user #If both email and password match then return user information
        except user_cls.DoesNotExist: #if user not exist then return None
            return None
        except: #got any error in middle return None
            return None

    def get_user(self, user_id):
        user_cls = get_user_model() #Get user object in one variable
        try:
            return user_cls.objects.get(pk=user_id) #check user with this user_id exist or not, may be PK (some unique id consider as an user_id)
        except user_cls.DoesNotExist: #if user_id(PK) not exist return None 
            return None

【讨论】:

  • 但是(email=username) 中的用户名是怎么来的呢?是因为def authenticate 它实际上是 django 的内置功能吗? def get_user 是如何使用的?如果在我的html 模板中没有这个,就会出现错误。
  • @Tsuna,可能在模型中是电子邮件,他们将用户名视为电子邮件,因此他们正在将用户名与电子邮件进行比较。 get_user 是他们创建的一个函数,用于检查特定用户数据(pk)在数据库中是否可用。如果没有这个,您的模板可能无法正常工作,因为他们可能在模板中调用了这个函数,参数为 user_id。
猜你喜欢
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 2015-01-20
  • 2020-04-08
相关资源
最近更新 更多