Django管理员表单用来创建扩展的AbstractUser模型

5 投票
1 回答
4485 浏览
提问于 2025-04-18 06:45

我有一个自定义的用户模型,它是从AbstractUser继承而来的。我还想让管理员中的用户创建表单与这个模型匹配,但不知为什么,我只能看到用户名和密码这两个字段,其他的都不显示。

让我觉得特别有趣的是,我在admin.py中对这三个字段所做的修改会在创建表单中反映出来,比如我可以改变密码1的帮助文本或标签,这些变化会在表单中显示,但其他字段就是不出现。

另外,如果我扩展UserAdmin并注册它(如下代码所示),我会得到一个普通用户的三个字段创建视图,但如果我扩展ModelAdmin,我就能看到我所有的字段,但无法使用密码更新表单,结果会出现404错误。

值得注意的是,进入对象列表的链接是“User”,而不是我模型的名称“CommonUser”,这可能是某个类的元信息设置的问题。


admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from models import CommonUser, Account, Registry
from django import forms


class MyUserChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = CommonUser


class MyUserCreationForm(UserCreationForm):

 password = forms.CharField(
    label='Password',
    max_length = 32,
    required=True,
    widget=forms.PasswordInput,
    )

password2 = forms.CharField(
    label='Confirm',
    max_length = 32,
    required=True,
    widget=forms.PasswordInput,
    help_text="Make sure they match!",
    )


class Meta(UserCreationForm.Meta):
    model = CommonUser
    fields = ['username', 'password', 'password2', 'email',
        'first_name','last_name','address','city','state','zipcode',
        'phone1','phone2',]
    help_texts = {
        'password': 'Must be at least 8 characters.',
    }


def clean_username(self):
    username = self.cleaned_data['username']
    try:
        CommonUser.objects.get(username=username)
    except CommonUser.DoesNotExist:
        return username
    raise forms.ValidationError(self.error_messages['duplicate_username'])


class MyUserAdmin(UserAdmin):
    form = MyUserChangeForm
    add_form = MyUserCreationForm
    fieldsets = UserAdmin.fieldsets + (
        ('Personal info', {'fields': ('address', 'phone1',)}),
    )

admin.site.register(CommonUser, MyUserAdmin)

(model.py的片段)

from django.contrib.auth.models import AbstractUser

class CommonUser(AbstractUser):
    "User abstraction for carrying general info."

    WORK_STATES = (
            ('FL', 'FL'),
        )

    address = models.CharField(max_length=50)
    city = models.CharField(max_length=30)
    state = models.CharField(max_length=2, default='FL', choices=WORK_STATES)
    zipcode = models.CharField(max_length=10)
    phone1 = models.CharField(max_length=15)
    phone2 = models.CharField(max_length=15, null=True)
    gets_email_updates = models.BooleanField(default=False)

来源

在Django的管理员中扩展新用户表单 为自定义用户模型使用Django认证UserAdmin https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#a-full-example

1 个回答

16

django.contrib.auth.admin里的UserAdmin也设置了一个叫“add_fieldsets”的属性,这个属性决定了在添加用户时显示哪些字段。因为UserAdmin已经设置了这个属性,所以你需要重新定义它,来设置你想要的字段。

下面是一个例子:

class CustomUserAdmin(UserAdmin):
# ...code here...

    fieldsets = (
        (None, {'fields': ('email',)}),
        (_('Personal info'), {'fields': ('first_name', 'last_name')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'first_name', 'last_name', 'password1',
                       'password2')}
         ),
    )

希望这对你有帮助!

撰写回答