修改django的用户名政策? [英] Modify django's username policy?
问题描述
Django默认的管理员身份验证模块不允许在用户名中使用 \
char.我该如何接受它?
Django default admin authentication module disallows use of the \
char in usernames. How can I make it accept it?
似乎可以编辑 contrib/auth/models.py
的用户名字段的验证器,但这不会这样做,因为它需要更改Django的基本代码.
It looks like it's possible to edit contrib/auth/models.py
's username field's validator, but that won't do because it requires a change to django's base code.
推荐答案
您可以使用自定义用户模型以实现这一目标.确保在模型定义中设置 USERNAME_FIELD
和 REQUIRED_FIELDS
,并在设置中设置 AUTH_USER_MODEL
.
You can use custom regex validators and a custom user model in order to achieve this. Be sure to set USERNAME_FIELD
and REQUIRED_FIELDS
in your model definition and AUTH_USER_MODEL
in your settings.
custom_userprofile_app.models.py
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer.'),
validators=[
validators.RegexValidator(r'^(.*)$',
_('Enter a valid username. '
'This value may contain any characters', 'invalid'),
validators.MinLengthValidator(5, 'Username must be at least 5 characters'),
],
error_messages={
'unique': _("A user with that username already exists."),
})
# The rest of your fields, etc
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email','first_name','last_name']
settings.py
AUTH_USER_MODEL = 'custom_userprofile_app.User'
这篇关于修改django的用户名政策?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!