django-registration 实际上不是这里的问题。问题是我已经继承了它的 RegistrationForm,用新的 help_text 重新定义了用户名字段。这样做,我阻止了它使用自己的正则表达式字段。为了解决这个问题,我不得不从 RegistrationForm 中提取一些零碎的东西到我的 EnhancedRegistrationForm 子类中。
注意正则表达式行,它反映了旧式用户名字符限制(这是我想要的)。
from registration.forms import RegistrationForm
# Carry these over from RegistrationForm - needed in the form definition below
attrs_dict = {'class': 'required'}
from django.utils.translation import ugettext_lazy as _
class EnhancedRegistrationForm(RegistrationForm):
first_name = forms.CharField(label='first name', max_length=30, required=True)
last_name = forms.CharField(label='last name', max_length=30, required=True)
username = forms.RegexField(regex=r'^\w+$',
max_length=30,
widget=forms.TextInput(attrs=attrs_dict),
help_text='Email addresses cannot be used as usernames.',
required=True,
label=_("Username"),
error_messages={'invalid':"You cannot use an email address as a username, sorry."})
class Meta:
fields = ('first_name','last_name','username','email','password1','password2')
def save(self, *args, **kwargs):
"""
Overriding save, so call the parent form save and return the new_user
object.
"""
new_user = super(EnhancedRegistrationForm, self).save(*args, **kwargs)
new_user.first_name = self.cleaned_data['first_name']
new_user.last_name = self.cleaned_data['last_name']
new_user.save()
return new_user