Django管理表单用于创建AbstractUser扩展模型

时间:2022-03-29 15:52:25

I've got a custome user model that extends/inherits AbstractUser. I also want the user creation form in admin to match, but for some reason I can only get it to show Username and Password fields. Nothing else.

我有一个扩展/继承AbstractUser的用户模型。我还希望管理员中的用户创建表单匹配,但由于某种原因,我只能让它显示用户名和密码字段。没有其他的。

What I find particularly interesting is that the changes I makes to those 3 fields in my admin.py reflect in the creation form, but the additional fields never show up. So for example I can change the helptext or label of a password1 and is renders that in the form, but the other fields don't.

我发现特别有趣的是,我对admin.py中的这三个字段所做的更改反映在创建表单中,但其他字段从不显示。例如,我可以更改密码1的帮助文本或标签,并在表单中呈现,但其他字段则不会。

Also, if I set extend UserAdmin and register that (as is shown in the code below) I get the 3 field creation view of a generic user, but if I extend ModelAdmin I get ALL my fields, but can't use the password update form. It 404s.

此外,如果我设置扩展UserAdmin并注册(如下面的代码所示),我得到一个普通用户的3字段创建视图,但如果我扩展ModelAdmin我得到所有的字段,但不能使用密码更新形成。它404s。

Of note also is that the link into the object list is 'User', not 'CommonUser' as my model is called, but that is probably a class meta somewhere.

值得注意的是,进入对象列表的链接是'User',而不是'CommonUser',因为我的模型被调用,但这可能是某个类元。


admin.py

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)

(snippet of) model.py

(片段)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)

sources

来源

Extending new user form, in the admin Django Using Django auth UserAdmin for a custom user model https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#a-full-example

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

1 个解决方案

#1


7  

UserAdmin from django.contrib.auth.admin also sets the "add_fieldsets" attribute, that sets the fields to be shown on the add user view. Since UserAdmin sets this field you need to overwrite it to set your own fields.

来自django.contrib.auth.admin的UserAdmin还设置“add_fieldsets”属性,该属性设置要在添加用户视图上显示的字段。由于UserAdmin设置此字段,您需要覆盖它以设置自己的字段。

Here is an example:

这是一个例子:

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')}
         ),
    )

Hope this helps!

希望这可以帮助!

#1


7  

UserAdmin from django.contrib.auth.admin also sets the "add_fieldsets" attribute, that sets the fields to be shown on the add user view. Since UserAdmin sets this field you need to overwrite it to set your own fields.

来自django.contrib.auth.admin的UserAdmin还设置“add_fieldsets”属性,该属性设置要在添加用户视图上显示的字段。由于UserAdmin设置此字段,您需要覆盖它以设置自己的字段。

Here is an example:

这是一个例子:

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')}
         ),
    )

Hope this helps!

希望这可以帮助!