修改django的用户名政策? [英] Modify django's username policy?

查看:69
本文介绍了修改django的用户名政策?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

推荐答案

您可以使用自定义

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆