python - 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
解决方案
你真的replace
不能这样。切片字符串会更好。
>>> username = '8username'
>>> bad_prefix = '8'
>>> good_prefix = '+7'
>>> if username.startswith(bad_prefix): username = good_prefix + username[len(bad_prefix):]
>>> username
'+7username'
推荐阅读
- stm32 - 通过 USART 访问 STM32L4 引导加载程序:无 ACK
- android - Android:想要但没有调用,实际上,与这个模拟的交互为零
- python-3.x - AttributeError:“loginUser”对象没有属性“var”
- javascript - 为 array.push() 中的对象命名
- python - 打印输出的最后一行缺少符号
- firebase - 如何知道在 Flutter 应用中使用哪个版本的 Google Firebase 插件?
- sql - PL/SQL 创建一个根据日期范围检查 SYSDATE 的触发器
- python - 在 jinja2 中访问烧瓶动态路由值
- function - Python - 函数中的变量未定义
- python - 如何使用 Python 从 Chrome 获取下载目录位置