django用户中的多个登录字段 [英] Multiple login fields in django user

查看:76
本文介绍了django用户中的多个登录字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Django用户时,是否可以使用多个登录字段?
就像在Facebook中,我们可以使用用户名,电子邮件和电话号码登录。

While using Django user is it possible somehow to use multiple login fields? Like in Facebook where we can login using username, email as well as the phone number.

推荐答案

是的,它是!您可以编写自己的身份验证后端,如本节所述:
https ://docs.djangoproject.com/en/1.8/topics/auth/customizing/

Yes, it is! You can write your own authentication backend, as this section describes: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/

我们假设您已经创建了一个应用程序帐户/附加电话字段的用户模型。
在account /中创建您的auth backends.py并编写您自己的身份验证逻辑。例如:

We suppose you have created an application account/ where you extend the User model for the additional phone field. Create your auth backend backends.py inside account/ and write you own authentication logic. For example:

from account.models import UserProfile
from django.db.models import Q


class AuthBackend(object):
    supports_object_permissions = True
    supports_anonymous_user = False
    supports_inactive_user = False


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


    def authenticate(self, username, password):
        try:
            user = UserProfile.objects.get(
                Q(username=username) | Q(email=username) | Q(phone=username)
            )
        except UserProfile.DoesNotExist:
            return None

        return user if user.check_password(password) else None

将自定义后端放在项目的settings.py中:

Put you custom backend in you project's settings.py:

AUTHENTICATION_BACKENDS = ('account.backends.AuthBackend',)

然后只需通过传递用户名,电子邮件或电话进行身份验证在POST的用户名字段中。

Then just authenticate by passing username, email or phone in the POST's username field.

from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
        else:
            # Return a 'disabled account' error message
            ...
    else:
        # Return an 'invalid login' error message.
        ...

请参阅: https://docs.djangoproject.com/fr/1.8/topics/auth/default/

这篇关于django用户中的多个登录字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆