How to Add User Profile in Django Admin?

Published On: 16/11/2022 | Category: Django


Hi Dev,

This post is focused on how to add user profile in django admin. we will help you to give example of how to create user profile in django admin. This article goes in detailed on how to create user and user profile in a django admin. I would like to share with you django admin add user profile.

The default Django User model can be extended in a number of different ways. The extension of the User model using a one-to-one link is arguably the most popular (and least intrusive) method. This tactic is also referred to as User Profile. If you're using Django Admin, one of the difficulties of this specific approach is figuring out how to display the profile information in the User edit page. And that is the topic of this tutorial.

Here i explained simply step by step example of how to add user profile in django admin.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example

Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python manage.py startapp core

Step 3: Update setting.py

In this step we require to do two things in our settings.py file, One is our installed app name Add the below lines to your settings.py file:

Next, you need to add it in the settings.py file as follows:

example/settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]

Step 4: Create a Model

In this step we will require the database model for storing contacts.Open the core/models.py file and add the following code:

core/models.py
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User

class Profile(models.Model):
    STUDENT = 1
    TEACHER = 2
    SUPERVISOR = 3
    ROLE_CHOICES = (
        (STUDENT, 'Student'),
        (TEACHER, 'Teacher'),
        (SUPERVISOR, 'Supervisor'),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    location = models.CharField(max_length=30, blank=True)
    birthdate = models.DateField(null=True, blank=True)
    role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True)

    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python manage.py makemigrations
python manage.py migrate

What we want to accomplish is allow Django Admin users to edit the location, birthdate, and role fields.

Step 5: Update admin.py

It's a very easy trick. We will change the UserAdmin Django uses, add the profile instance as an inline, and extend the default UserAdmin.

What if we wanted to show the User location in the list view, which is defined in the profile model, as follows:

Finally we unregister the old User admin and register the new one, the custom with the Profile model.

core/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

from .models import Profile

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Profile'
    fk_name = 'user'

class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline, )
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'get_location')
    list_select_related = ('profile', )

    def get_location(self, instance):
        return instance.profile.location
    get_location.short_description = 'Location'

    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)

admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)


Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/admin address with a web browser.



I Hope It will help you....