简体   繁体   English

如何在 django 中自定义 UserCreationForm 验证

[英]How to customize UserCreationForm validation in django

I'm currently trying to build user registration form using UserCreationForm but it doesn't suit my needs.我目前正在尝试使用 UserCreationForm 构建用户注册表单,但它不适合我的需要。 First of all, Username field accepts not only alphabet symbols and digits but also @.首先,用户名字段不仅接受字母符号和数字,还接受@。 + - _. + - _。 I want to make it accept only latin and cyrillic leterrs and digits but I could not find any information.我想让它只接受拉丁文和西里尔文字母和数字,但我找不到任何信息。 Also i want to change it's other properties like maximum length.我也想改变它的其他属性,比如最大长度。 Also after we make these changes will both client and server sides validation process deny banned symbols?此外,在我们进行这些更改之后,客户端和服务器端的验证过程都会拒绝被禁止的符号吗?

Here is some code I already have in forms.py:这是我在 forms.py 中已有的一些代码:

class CreateUserForm(UserCreationForm):
class Meta:
    model = User
    fields = ['username', 'email', 'password1', 'password2']

and views.py:和views.py:

def register(request):
form = CreateUserForm()

if request.method == 'POST':
    form = CreateUserForm(request.POST)
    if form.is_valid():
        form.save()

context = {'form': form}
return render(request, 'register.html', context)

Also, is this default UserCreationForm relevant way to register user?另外,这是默认的 UserCreationForm 相关方式来注册用户吗? Or it would be better if I write my own one?还是我自己写一个会更好?

You have to know that UserCreationForm is basically a Django Form after all.你要知道UserCreationForm基本上是一个Django Form So form validation mechanics applies on it.所以表单验证机制适用于它。

As the docs mentions , you can validate a custom field by creating a method holding this name format: clean_<field name> , in your case its: clean_username . 正如文档所述,您可以通过创建一个保存此名称格式的方法来验证自定义字段: clean_<field name> ,在您的情况下为: clean_username

This is a sample of a field clean method:这是现场清洁方法的示例:

def clean_username(self):
    username = self.cleaned_data['username']
    # Do whatever you want
    if error_case: # Write your own error case.
        raise forms.ValidationError("Error Message") # Your own error message that will appear to the user in case the field is not valid
    return email # In case everything is fine just return user's input.

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

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