Django管理用户创建表单中未显示额外字段

时间:2019-07-08 17:46:52

标签: python django web django-rest-framework web-site-project

enter image description here enter image description here enter image description here 我写了form.py和admin.py。但是额外的字段(例如电子邮件,全名)不会显示在Django管理用户创建表单中。

2 个答案:

答案 0 :(得分:0)

在admin.py中尝试

# How to add a field to the Django Admin Add User form 
# using UserCreationForm. Add this to a admin.py and alter 
# to whatever fields you'd like

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib import admin

class UserCreationFormExtended(UserCreationForm): 
    def __init__(self, *args, **kwargs): 
        super(UserCreationFormExtended, self).__init__(*args, **kwargs) 
        self.fields['email'] = forms.EmailField(label=_("E-mail"), max_length=75)

UserAdmin.add_form = UserCreationFormExtended
UserAdmin.add_fieldsets = (
    (None, {
        'classes': ('wide',),
        'fields': ('email', 'username', 'password1', 'password2',)
    }),
)

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

答案 1 :(得分:0)

我检查了我的一个项目,这就是我的工作方式。

class UserAdmin(BaseUserAdmin):
    fieldsets = (
        (None, {'fields': ('cpf', 'password')}),
        ('Personal Info', {'fields': ('first_name', 'last_name')}),
        ('Permissions', {'fields': ('is_active', 'is_superuser', 'is_admin', 'groups', 'user_permissions')}),
        ('Important dates', {'fields': ('last_login',)}),
    )
    limited_fieldsets = (
        (None, {'fields': ('cpf',)}),
        ('Personal info', {'fields': ('first_name', 'last_name')}),
        ('Important dates', {'fields': ('last_login',)}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('cpf', 'password1', 'password2')
        }),
    )
    form = UserChangeForm
    add_form = UserCreationForm
    change_password_form = auth_admin.AdminPasswordChangeForm
    list_display = ('cpf', 'first_name', 'last_name', 'is_admin')
    list_filter = ('is_active', 'is_admin')
    search_fields = ('first_name', 'last_name', 'cpf')
    ordering = ('cpf',)
    readonly_fields = ('last_login',)
    filter_horizontal = ('groups', 'user_permissions')