带有自定义字段的Django 1.5 rc1管理员用户创建表单

时间:2013-02-07 20:47:13

标签: django django-admin

我找不到在管理员的“添加新用户页面”上显示自定义用户自定义必填字段的方法。

我创建了一个自定义用户,它扩展了AbstractUser并添加了三个必需的自定义字段。我没有创建自定义UserManager,因为我从AbstractUser扩展而不是AbstractBaseUser。

对于管理员方面: 1.我通过扩展它创建了一个自定义UserCreationForm。在元类中,我添加了新的三个自定义字段

但我无法在管理员端看到自定义字段。我做错了吗?

以下是管理员方面的代码:

class MyUserCreationForm(UserCreationForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = get_user_model()
        fields = ('customField1', 'customField2', 'customField3',)

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class MyUserAdmin(UserAdmin):
    form = MyUserChangeForm
    add_form = MyUserCreationForm

    fieldsets = (
        (None, {'fields': [('username', 'password', 'customField1', 'customField2', 'customField3'),]}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                   'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
        )



admin.site.register( CustomUser, MyUserAdmin)

1 个答案:

答案 0 :(得分:4)

解决方案---在扩展的UserAdmin类中添加“add_fieldsets”会显示字段。

add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'password1', 'password2', 'customField1', 'customField2', 'customField3', )} ),