默认情况下,Django用户名区分大小写。显然,这是won't be fixed。
这可能是一个好功能,特别是如果不允许使用其他字符。例如,我自己的用户名可能看起来更好,如StringsOnFire。但是,默认情况下,无法通过用户名为用户提供唯一的URL。
我想:
contrib.auth
用户模型保持不变可能的解决方案是什么?哪种方法最好?
您可以使用CustomUserManager
,并在CustomUserManager
方法中,进行不区分大小写的检查,以查看用户名是否已经与create_user()
一起使用
我使用django_registration(iexact
)中的RegistrationFormCaseInsensitive表单来做
安装后:
在admin.py中:
def clean_username(self):
kwargs = {
'{0}__{1}'.format(UsernameField(), 'iexact'): self.cleaned_data['username'],
}
if User.objects.filter(**kwargs):
raise ValidationError(_('A user with that username already exists.'), code='invalid')
return self.cleaned_data['username']
使用以下方式创建forms.py:
https://pypi.org/project/django-registration/
在urls.py中添加以下导入之一:一步注册:
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
pass
或用于通过邮件链接进行注册:
from django_registration.forms import RegistrationFormCaseInsensitive
from .models import CustomUser
class CustomUserForm(RegistrationFormCaseInsensitive):
class Meta(RegistrationFormCaseInsensitive.Meta):
model = CustomUser
然后添加路径:
from django_registration.backends.one_step.views import RegistrationView