首页 > 解决方案 > Django检查用户名是否以特殊字符开头并将其更改为使用更改的用户名进行身份验证

问题描述

这是我的自定义身份验证后端。我想检查用户名是否以某个字符开头并将这个字符更改为新的字符串或字符。

class PhoneAuthBackend(object):
    def authenticate(self, request, username=None, password=None):
        try:
            user = User.objects.get(username=username)
            if username.startswith('8'):
                username[0].replace('+7')
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

我试过了:

class PhoneAuthBackend(object):
    def authenticate(self, request, username=None, password=None):
        try:
            user = User.objects.get(username=username)
            bad_prefix = '8'
            good_prefix = '+7'
            if username.startswith(bad_prefix):
                username = good_prefix + username[len(bad_prefix):]
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

它不起作用。

如果我使用此代码,它也不起作用:

            if username.startswith(bad_prefix):
                new_username = good_prefix + username[len(bad_prefix):]
            user = User.objects.get(new_username=username)

解决方案:

class PhoneAuthBackend(object):
    def authenticate(self, request, username=None, password=None):
        try:
            bad_prefix = '8'
            good_prefix = '+7'
            if username.startswith(bad_prefix):
                username = good_prefix + username[len(bad_prefix):]
            user = User.objects.get(username=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

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

标签: pythondjangodjango-authentication

解决方案


你真的replace不能这样。切片字符串会更好。

>>> username = '8username'
>>> bad_prefix = '8'
>>> good_prefix = '+7'
>>> if username.startswith(bad_prefix): username = good_prefix + username[len(bad_prefix):]
>>> username
'+7username'


推荐阅读