gpt4 book ai didi

python - Django : Case insensitive matching of username from auth user?

转载 作者:太空狗 更新时间:2023-10-29 17:22:33 26 4
gpt4 key购买 nike

默认情况下,Django 将用户名实现为区分大小写,现在为了身份验证,我编写了自己的 Authentication Backend 以在身份验证时处理不区分大小写的用户名。

如图:http://blog.shopfiber.com/?p=220

现在,问题是:

我有各种 View 和实用方法,可以将 username 与一些 stings 进行比较。

request.user.username == username_from_some_other_system_as_str

现在,如果用户名是 yugal 那么:

request.user.username == 'Yugal' # Returns False

现在,它应该返回 True [我想要实现的目标]

为此,我记得 C++ 时代,运算符重载。但我不认为简单地为 django 的 auth user 这样做是个好主意,因为 auth userdjango 紧密绑定(bind)。此外,重载 == 将使整个类不区分大小写,而不仅仅是 username 字段。

那么,即使在整个比较过程中,我应该如何处理这个 username 不区分大小写的问题。

注意:

  • 创建一个始终返回小写用户名的 get_username 方法是不可能的,因为它需要重构所有代码才能使用它。您可以为您的代码执行一次,但如果您使用的是第 3 方 Django 应用程序,则不可能。

  • 我知道 user.username.lower() = something.lower() 是可能的,但容易出错,而不是多开发人员设置中经常使用的东西的编写解决方案.

  • 我已尽可能使用 SomeModel.objects.filter(username__iexact=username)。但这仍然会使系统容易受到任何不知情的开发人员的错误影响。

======================================

从概念上找出了解决方案,但无法使其工作(帮助):

####### Custom CharField for username case-insensitivity #######
from django.db.models.fields import CharField
class iUnicode:
def __init__(self, value):
self.value = value

def __eq__(self, other):
if isinstance(other, str) or isinstance(other, unicode):
return self.value.lower() == other.lower()
if isinstance(other, self.__class__):
return other == self.value

def __unicode__(self):
return unicode(self.value)
def __str__(self):
return self.__unicode__()


class UsernameCharField(CharField):
def to_python(self, value): # Its not getting called
unicode_val = super(CharField, self).to_python(value)
return iUnicode(unicode_val)

if User._meta.local_fields[1].name == 'username':
User._meta.local_fields[1] = UsernameCharField(max_length=30)
User._meta.local_fields[1].model = User
################################################################

我假设 to_python 用于将从数据库接收到的值转换为 python 中的 unicode。但是,我想我的 to_python 没有被调用。

This will also ensure case-insensitivity in 3rd party apps and would not require any re-factoring. It will patch the User at its core. I will be adding this to __init__.py of my first INSTALLED_APP

我做错了什么?

最佳答案

从 Django 1.5 开始,让用户名不区分大小写很简单:

class MyUserManager(BaseUserManager):
def get_by_natural_key(self, username):
return self.get(username__iexact=username)

来源:1 , 2

关于python - Django : Case insensitive matching of username from auth user?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13190758/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com