0

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.

Gopal Singh
  • 23
  • 1
  • 5

2 Answers2

2

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'
  )
Sadan A.
  • 1,017
  • 1
  • 10
  • 28
1

use 'AbstractUser' model to Extend pre define user model in Django.

then we cam easily add some field or add more information in usermodel.

from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

Then we have to update our settings.py defining the AUTH_USER_MODEL property.

AUTH_USER_MODEL = 'core.User'

follow this link for more information:-https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html