Django:自定义用户模型字段没有出现在Django管理员中

时间:2018-05-17 16:08:07

标签: python django authentication django-models

我试图在django.contrib.auth.models用户模型中添加一些额外的字段。我将在整个项目中使用此自定义用户模型。我使用AbstractUser添加了namecontact字段。

class User(AbstractUser):
    name = models.CharField(_('Name of User'), blank=True, max_length=255)
    contact = models.CharField(max_length=20, blank=True)
    def __str__(self):
        return self.username

在我的settings.py中,我添加了apps.authentication,这是我的应用:

INSTALLED_APPS = [ 'apps.authentication', ...]

我还指定了我的AUTH_USER_MODEL

AUTH_USER_MODEL = 'authentication.User'

然后我运行了迁移并且它工作了(我检查了我的本地数据库;制作了新表)。但是,当我使用Django管理员访问它时,namecontact字段无处可寻。如何显示字段?

enter image description here

3 个答案:

答案 0 :(得分:7)

您可以通过在UserAdmin文件中添加以下内容,将自定义fieldsets附加到默认admin.py类:

from django.contrib.auth.admin import UserAdmin

UserAdmin.fieldsets += ('Custom fields set', {'fields': ('name', 'contact')}),

答案 1 :(得分:1)

我认为您缺少的部分是在应用的admin.py中注册您的用户模型:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User

admin.site.register(User, UserAdmin)

(摘自https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#specifying-a-custom-user-model

答案 2 :(得分:0)

虽然接受的解决方案确实有效,但它会将所有新字段放在页面的最底部。能够将字段追加到特定部分,并将字段从一个部分移动到另一个部分,这是很好的。

我使用这两个实用程序函数将字段追加到字段集并将字段从一个字段集移动到另一个:

common / utils / admin.py

def append_fields(fieldsets, section, fields):
    """
    fieldsets : tuple
        The fieldsets to append to.
            - fieldsets for editing existing objects
            - add_fieldsets for adding new objects
    section : str or None
        The title of the section. None for the titleless section.
    fields : tuple
        The fields being appended.
    """
    for fieldset in fieldsets:
        if fieldset[0] == section:
            fieldset[1]['fields'] += fields
            break 
    else: # Add new section
        fieldsets = fieldsets + (
            (section, {
                'classes': ('wide',),
                'fields': fields
            }),
        )
    return fieldsets

def move_field(fieldsets, field, from_section, to_section):
    """
    fieldsets : tuple
        The fieldsets to append to.
            - fieldsets for editing existing objects
            - add_fieldsets for adding new objects
    field: str
        The name of the field to move.
    from_section : str or None
        The title of the section from which to remove the field.
    to_section : str or None
        The title of the section in which to add the field.
    """
    for fieldset in fieldsets:
        if fieldset[0] == from_section:
            field_list = list(fieldset[1]['fields'])
            field_list.remove(field) # will raise exception if field not found
            fieldset[1]['fields'] = tuple(field_list)
            break
    else:
        raise Exception(f'No such from fieldset: {from_section}')

    for fieldset in fieldsets:
        print(fieldset)
        if fieldset[0] == to_section:
            fieldset[1]['fields'] = fieldset[1]['fields'] + (field, )
            break
    else:
        raise Exception(f'No such to fieldset: {to_section}')

然后将其导入我的CustomUserAdmin类中:

users / admin.py

from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin

from common.utils.admin import append_fields, move_field

CustomUser = get_user_model()

class CustomUserAdmin(UserAdmin):
    model = CustomUser

    # Fields for editing existing user
    new_fields = ('dob', 'avatar')
    fieldsets = append_fields(UserAdmin.fieldsets, 'Personal info', new_fields)
    move_field(UserAdmin.fieldsets, 'email', 'Personal info', None)

    # Fields for adding new user
    new_fields = ('email', )
    optional_fields = ('first_name', 'last_name', 'dob')
    add_fieldsets = append_fields(UserAdmin.add_fieldsets, None, new_fields)
    add_fieldsets = append_fields(
        UserAdmin.add_fieldsets, 'Optional Fields', optional_fields
    )


admin.site.register(CustomUser, CustomUserAdmin)