Django Custom Admin user management page

User management is usually the default admin pages and edit list and do not mind, we need to be customized to operate.

Add the following code admins.py, so that the user list to display more content.

from django.contrib import admin
 # 1. 导入默认UserAdmin 作为Base Class
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User

# 2.  Define a new User admin
class UserAdmin(BaseUserAdmin):
    # 3. 重新定义 list_display
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_active', 'date_joined', 'is_staff') 

# 4. 注销 User
admin.site.unregister(User)
# 5. 重新注册 User
admin.site.register(User, UserAdmin)

If your User model attributes associated with the other tables, such as UserProfile, and want to manage on the same page, the following way:

  1. In the last step, import your own Profile model
  2. Inline Class definitions
  3. Inline added information UserAdmin custom in
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from accounts.models import UserProfile


class UserProfileAdmin(admin.ModelAdmin):
    list_display = ['user', 'phone_number', 'gender', 'date_of_birth', 'address', 'suburb', 'city', 'post_code']


# Define an inline admin descriptor for Employee model
# which acts a bit like a singleton
class EmployeeInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'profile'


# Define a new User admin
class UserAdmin(BaseUserAdmin):
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_active', 'date_joined', 'is_staff')
    inlines = (EmployeeInline,)


# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
admin.site.register(UserProfile, UserProfileAdmin)

Reference documents:
https://www.jianshu.com/p/0a34918160ab

Guess you like

Origin www.cnblogs.com/hupingzhi/p/12600659.html