djangodjango-modelsdjango-admin-filtersdjango-admin-toolsdjango-admin-actions

User Model Customisation in Django


I want to edit the User Model in admin.py but I am not able to figure out how can I do this? Here is the Image of Admin Panel of User Model

Can someone please help me? I want to add some customized fields in the User model.


Solution

  • You can do that by extending AbstractUser from django.

    # models.py
    
    from django.contrib.auth.models import AbstractUser
    from django.db import models
    from django.utils.translation import gettext_lazy as _
    
    
    class User(AbstractUser):
        EMAIL_FIELD = 'email'
        USERNAME_FIELD = 'email'
        REQUIRED_FIELDS = ['username']
    
        email = models.EmailField(
            _('email address'),
            unique=True,
            blank=True
        )
        cellphone = models.CharField(
            _('cell phone'),
            max_length=20,
            null=True, blank=True
        )
    

    Then you also need to specify this Custom user model in your settings. Specify path to the user model you've just created. <app_name>.<ModelClassName>

    # settings.py
    
    AUTH_USER_MODEL = 'users.User'
    

    Lastly, your admin must also inherit from Django default UserAdmin, if you want to save your time from all the hassle of creating some methods they have already created. Now you can edit user admin the way you want by also getting advantage of all the existing admin features.

    # admin.py
    
    from django.contrib.auth import get_user_model
    from django.contrib.auth.admin import UserAdmin as OrigUserAdmin
    
    User = get_user_model()
    
    
    @admin.register(User)
    class UserAdmin(OrigUserAdmin):
      list_display = (
        'id', 'first_name', 'last_name', 'username', 'email', 'is_active'
      )