我正在使用Django 1.3 / Python 2.7。
我的应用程序使用django.contrib.auth进行用户管理。对于主要用户注册,我有一个表格,检查“电子邮件”是否已经注册。因此,它确保所有电子邮件字段都是唯一的。
但有些管理员会使用django管理界面添加用户,并最终使用相同的电子邮件添加重复的帐户。
为此,我创建了一个NewUserCreationForm,在那里我复制了django.contrib.auth.UserCreationForm,并为其添加了一个“email”字段。
class NewUserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and password.
"""
username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput,
help_text = _("Enter the same password as above, for verification."))
email = forms.EmailField(label=_("Email"), max_length=75)
class Meta:
model = User
fields = ("username", "email")
def clean_username(self):
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(_("A user with that username already exists."))
def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2
def save(self, commit=True):
user = super(NewUserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.email = self.email
if commit:
user.save()
return user
class CustomUserAdmin(UserAdmin):
add_form = NewUserCreationForm
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
但是这段代码不起作用。我可以看到表单呈现,但没有电子邮件字段,只有Username,password1和password2字段。
我在这里失踪的是什么?
答案 0 :(得分:3)
您缺少... UserAdmin.add_fieldsets,例如:
class CustomUserAdmin(UserAdmin):
add_form = NewUserCreationForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'email')}
),
)