Custom User model fields (AbstractUser) not showing in django admin

前端 未结 3 1802
独厮守ぢ
独厮守ぢ 2021-02-05 10:00

I have extended User model for django, using AbstractUser method. The problem is, my custom fields do not show in django admin panel.

My models.py:

from          


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-02-05 10:46

    The quickest way to show your extra fields in the Django Admin panel for an AbstractUser model is to unpack the UserAdmin.fieldsets tuple to a list in your admin.py, then edit to insert your field/s in the relevant section and repack as a tuple (see below).
    Add this code in admin.py of your Django app

    from django.contrib import admin
    from django.contrib.auth.admin import UserAdmin
    from .models import User
    
    fields = list(UserAdmin.fieldsets)
    fields[0] = (None, {'fields': ('username', 'password', 'is_bot_flag')})
    UserAdmin.fieldsets = tuple(fields)
    
    admin.site.register(User, UserAdmin)
    

    Note:
    list(UserAdmin.fieldsets) gives the following list:

    [  (None, {'fields': ('username', 'password')}), 
       ('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')})
    ]
    

    These fields are by default in Django user models, and here we are modifying the first index of the list to add our custom fields.

提交回复
热议问题