如何自定义用户名验证 [英] How to customize username validation

查看:62
本文介绍了如何自定义用户名验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 django.contrib.auth自定义用户名验证用户模型.它说用户名可能包含字母数字,_,@,+ 、.和-字符.,但我想这样做,以便如果用户使用 @,.,-,+ 来创建用户名,该密码将无效.我将如何覆盖此验证,以便当用户创建用户名时,它使用的是我的自定义验证,而不是原始的 UnicodeUsernameValidator ?

I am trying to customize username validation for the django.contrib.auth User model. It says Usernames may contain alphanumeric, _, @, +, . and - characters. but I'd like to make it so that it would be invalid if the user made a username with @, ., -, +. How would I go about overriding this validation so when the user creates a username it is using my custom validation instead of the original UnicodeUsernameValidator?

我正在使用自己的自定义用户模型,但是我是从 AbstractBaseUser 继承的?是否有一种简单的方法来添加我的用户名验证?

I am using my own custom User model, but i'm inheriting from AbstractBaseUser Is there a simple way to add my username validation?

推荐答案

有一个

There is a username_validator property that you can set on your model class:

指向用于验证用户名的验证器实例.默认为 validators.UnicodeUsernameValidator .

要更改默认的用户名验证器,可以对 User 模型进行子类化,然后将此属性设置为其他验证器实例.例如,要使用ASCII用户名:

To change the default username validator, you can subclass the User model and set this attribute to a different validator instance. For example, to use ASCII usernames:

from django.contrib.auth.models import User
from django.contrib.auth.validators import ASCIIUsernameValidator

class CustomUser(User):
    username_validator = ASCIIUsernameValidator()

这篇关于如何自定义用户名验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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