Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有人能帮我举个例子吗?德扬戈_Python_Django_Login_Model - Fatal编程技术网

Python 有人能帮我举个例子吗?德扬戈

Python 有人能帮我举个例子吗?德扬戈,python,django,login,model,Python,Django,Login,Model,我在网上找到了一个脚本,它可以帮助我将登录名改为同时使用用户名和电子邮件,而不仅仅是用户名,但是有很多部分我并不真正理解 比如,我非常理解每一行的意思,但我不明白为什么这样做会使我的登录工作与电子邮件 class EmailBackend(object): def authenticate(self, username=None, password=None): user_cls = get_user_model() try: us

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

比如,我非常理解每一行的意思,但我不明白为什么这样做会使我的登录工作与电子邮件

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
提前感谢。

查看评论:-

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

此脚本使用用户名标题而不是电子邮件,但在后端,此用户名必须是电子邮件用户=user\u cls.objects.getemail=username您可以将用户名更改为电子邮件,这并不重要。但是,电子邮件中的用户名=username是如何获得的?是否因为def身份验证,它实际上是django中内置的?def get_用户是如何使用的?在我的HTML模板中没有这个会有一个错误。@津名,在模型中可能是电子邮件,他们把用户名看作是电子邮件,所以他们正在比较用户名和电子邮件。get_user是他们创建的一个函数,用于检查特定用户datapk是否在数据库中可用。如果没有此选项,您的模板可能无法工作,因为他们可能在其in模板上调用了此函数,参数为user_id。