Django 1.5 rc1管理用户创建表单与自定义字段

6

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

我创建了一个扩展自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)

4
解决方案 --- 在扩展的UserAdmin类中添加 'add_fieldsets' 可以使字段出现。 add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'password1', 'password2', 'customField1', 'customField2', 'customField3', )} ), - ratata
嘿 @ratata,你能把你的解决方案发布为答案吗?这样我们就可以将其标记为已回答! - Azd325
1个回答

4
解决方案 --- 在扩展的UserAdmin类中添加'add_fieldsets'使字段显示。
add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'password1', 'password2', 'customField1', 'customField2', 'customField3', )} ),

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接