简体   繁体   English

Django不区分大小写的登录,混合大小写的用户名

[英]Django case insensitive login, mixed case username

I'm trying to do case insensitive login for a Django app, without altering original username case. 我正在尝试为Django应用程序进行不区分大小写的登录,而不会更改原始用户名案例。 According to my research, the best approach is to create a related field to store the username in lowercase at registration. 根据我的研究,最好的方法是创建一个相关字段,以便在注册时以小写形式存储用户名。 No reinventing the user model, it's a simple solution, right? 没有重塑用户模型,这是一个简单的解决方案,对吧? My dilemma: How to do you take data from one model, change it, and save it in another model when the object is created? 我的困境:如何从一个模型中获取数据,更改它,并在创建对象时将其保存在另一个模型中?

Here is what is in models.py : 这是models.py中的内容

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    lc_n = User.username
    lc_n = lc_n.lower()
    lowercase_name = models.CharField(max_length=30, default=lc_n)

When running python manage.py makemigrations there is the following error: 运行python manage.py makemigrations出现以下错误:

AttributeError: type object 'User' has no attribute 'username'

User does have that attribute, but it can't be accessed this way. 用户确实具有该属性,但无法以这种方式访问​​。

Please forgive me, as this must contain some simple fundamental flaw. 请原谅我,因为这必须包含一些简单的基本缺陷。 Any support that may be offered will be greatly appreciated. 我们将非常感谢您提供的任何支持。

You don't need any additional models to implement case insensitive login. 您不需要任何其他模型来实现不区分大小写的登录。 Django supports case insensitive filtering by iexact operator: Django支持iexact运算符的不区分大小写的过滤:

user = User.objects.get(username__iexact=name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM