【发布时间】:2017-02-10 13:21:23
【问题描述】:
我正在尝试允许在默认 django.contrib.auth.models 用户的用户名字段中接受空格,其他人之前曾直接或类似问题提出过:Here、Here 和 Here .我试图实施这些建议,但是我似乎找不到一个很好的例子来说明如何让它发挥作用。
据我了解,我需要更改用户名字段验证器中的正则表达式,为此我可以覆盖 contrib.auth.forms 中的 UserCreationForm 以实现用户名的不同字段并提供我自己的验证。 (如this 回答中所建议的那样)。
我具体怎么做?
作为参考,这是我目前用作注册表单的内容:
class SignUpForm(forms.ModelForm):
"""
This form class is for creating a player
"""
username = forms.CharField(label='Gamertag', max_length=16, widget=forms.TextInput(attrs={'placeholder': 'Gamertag', 'class': 'form-input'}))
email = forms.EmailField(label='email', widget=forms.TextInput(attrs={'placeholder': 'Email', 'class': 'form-input', 'type':'email'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-input'}))
class Meta:
model = User
fields = ['username',
'email',
'password']
widgets = {
'password': forms.PasswordInput(),
}
def clean_email(self):
email = self.cleaned_data.get('email')
username = self.cleaned_data.get('username')
if email and User.objects.filter(email=email).exclude(username=username).count():
raise forms.ValidationError(u'A user with that email already exists.')
return email
【问题讨论】:
-
你运行的是哪个版本的 Django?
-
我的Django版本是1.10.1
标签: python django django-models django-forms django-admin