How to Customize Django Admin Dashboard Site?
Do you want to customize your Django Admin site so that it will be easier for you to track all the users and model data on the Django admin interface?
In an earlier tutorial, we have seen how to add a model to the Django admin site. I will be sharing some important tricks and tips to help you out customizing your Django admin site based on your requirements.
Before we start to customize Django admin dashboard, lets consider we have Django model.
class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.IntegerField(blank=True, null=True) city = models.CharField(max_length=200, default="", null=True) country = models.CharField(max_length=200, default="", null=True)
Here, “user” is the key inherited from the actual Django “User” model.
First of all, create
admin.py file in your working directory (in the same directory where models.py present) if it is not present.
You can login to your admin panel by hitting admin url.
If you are running your Django site locally, here is the URL.
Now you can see the default Django admin dashboard but you not see any model data as we have not registered them to our admin interface.
1. How to show all the fields from model?
You have to register for the class and make a list of all the fields (
list_display) that you want to show in the admin dashboard. Here is the sample code.
from django.contrib import admin from .models import ProfileModel @admin.register(ProfileModel) class ProfileAdmin(admin.ModelAdmin): list_display = [field.name for field in ProfileModel._meta.get_fields()]
Here, we are using the list comprehension technique to get the list of all the fields from the profile model and assigning them to the list “list_display”.
Save the file and run the Django server. If you open the admin interface, you will see the “ProfileModel” where you can see all the profiles. You can also delete and edit the profile entries.
Similarly, you to have write the class for all the models to show them in admin site. Its pretty easy, isn’t it?
Let’s see some of the very important and required customization for Django admin interface.
2. How to add field from another model?
Let’s say you want to add the email ID in the user profile from Django User modal. Here is the sample code.
from django.contrib import admin from .models import ProfileModel @admin.register(ProfileModel) class ProfileAdmin(admin.ModelAdmin): list_display = [field.name for field in ProfileModel._meta.get_fields()] list_display.append('email') def email(self, obj): return obj.user.email
It will append the field “email” to the “ProfileModel” in your Django admin.
Note: The name of the function and field should be the same.
I will keep adding more ways to customize Django admin dashboard site. Let me know if you have specific requirements to customize the Django admin interface. I would like to help you out.