Don't miss this free $200 USD credit (Valid for 60 days) on DO, launch your idea now

You have no excuses now, use this free credit to launch your projects now on Digital Ocean, you're free to spend it whenever you want within the following 60 days.

Table of contents

The django admin panel and its customization

The django admin panel and its customization

One of the best features of django is that it has the django admin panel, a ready-to-use administration panel, with basic functions such as create, read, edit and delete models, users, groups and permissions. All ready to use just by setting up your application. But sometimes our needs are different, what if we want to modify the appearance or functions of the interface? Fortunately Django includes many functions to customize the behavior of the admin, I will explain some of them below.

The django admin panel is so well designed, and it works out of the box, is definitely one of the reasons why you should consider using Django instead of other frameworks.

Checking that django admin panel is active

If you started your project with the startproject command, the django administration panel will be activated by default. If you go to /admin/ the login screen will appear.

Administration panel login screen
django admin panel screen

If not, or if you start from a previous installation, you must first make sure that it is installed in your configuration file, as well as its dependencies:

  • django.contrib.auth
  • django.contrib.contenttypes
  • django.contrib.messages
  • django.contrib.sessions

After all, if you can’t authenticate or log in, you won’t be able to enter the administration panel, will you?

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    # ...
]

You must also add django.contrib.messages.context_processors.messages and django.contrib.auth.context_processors.auth to the context_processors option in the TEMPLATES variable of your settings.py file.

In the same way add django.contrib.auth.middleware.AuthenticationMiddleware and django.contrib.messages.middleware.MessageMiddleware to the MIDDLEWARE variable of your settings.py file as well.

Now that we are sure that the admin package is active, let’s start by adding a model. I’m going to use a hypothetical model called Videogame that looks like this

# videogameStore/models.py
from django.db import models
GENRES = (
        ('HR', 'Horror'),
        ('AD', 'Adventure')
    )

class Videogame(models.Model):
    name = models.CharField(max_length=256)
    description = models.TextField(blank="true")
    genre = models.CharField(choices=GENRES, max_length=2)
    rating = models.FloatField()
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

Adding a template to the django admin panel

Let’s start with the basics, adding a model to the admin.

# videogameStore/admin.py
from django.contrib import admin
from .models import Videogame

admin.site.register(Videogame)

With this we will have a modifiable model in the admin.

If we enter the url /admin/ and log in, we will be able to see the interface working.

django administration panel

Note the absence of the search bar

If we click on the gray button in the upper right corner we can add a model.

Modifying the fields that appear in django admin

In the admin.py file inside our Django application we are going to inherit from the admin.ModelAdmin class.

We can endow this model with the list_display property, to tell the admin which fields we want to list in the manager.

The search_field property allows us to specify on which fields the search will be performed.

# videogameStore/admin.py
from django.contrib import admin
from .models import Videogame

class VideogameAdmin(admin.ModelAdmin):
      list_display = ('name', 'created') #now this field should show more data about
      search_fields = ('name', 'description')

admin.site.register(Videogame, VideogameAdmin)

django admin admin panel with the created field and search bar added

See the created field and the search bar

Change the order of the fields when editing

If we want to modify the order of the fields we add a fields property to our class

# videogameStore/admin.py
from django.contrib import admin
from .models import Videogame

class VideogameAdmin(admin.ModelAdmin):
      list_display = ('name', 'created') 
      search_fields = ('name', 'description')
      fields = ('description', 'name', 'genre', 'rating')
admin.site.register(Videogame, VideogameAdmin)

As you can see, the order in which the fields appear has been modified. In order Description, Name, Genre and Rating, just as we specified.

Order of the modified model creation formulary according to the fields field

Notice how the order has changed from that specified in the fields property.

Sorting objects by a field

Ordering specifies the field to be used for ordering the models.

# videogameStore/admin.py
from django.contrib import admin
from .models import Videogame

class VideogameAdmin(admin.ModelAdmin):
      list_display = ('name', 'created') 
      search_fields = ('name', 'description')
      fields = ('description', 'name', 'genre', 'rating')
      ordering = ('-name',)
admin.site.register(Videogame, VideogameAdmin)

Here we have told you to order them by name, in descending order, using the “-” symbol.

Models sorted alphabetically in descending order

Note the arrangement of the models in descending order

Modifying the header, title and description on django admin page

If you want to give a personalized touch to the Django admin, even giving it the name of your business, or your client’s business. You can do this by modifying the properties of the Admin model as follows:

# videogameStore/admin.py
# ...
admin.site.site_header = 'Site name'
admin.site.index_title = 'Control panel of the site'
admin.site.site_title = 'title in the browser tab'

Now you can see that in the main page of the admin you can see the changes we have made.

Changing the title, description and title of the django admin panel

The three sites have changed

Sorting objects according to a date field

If we add a date_hierarchy field to our model, we will be able to sort the fields according to a DateTimeField or DateField type field in our model.

# videogameStore/admin.py
from django.contrib import admin
from .models import Videogame

class VideogameAdmin(admin.ModelAdmin):
    # ...
    date_hierarchy = 'created'
admin.site.register(Videogame, VideogameAdmin)

Sorting by date field

The legend April2021 and April 30 appear after placing date_hierarchy

Create custom dynamic fields

We can also create special fields, which are not part of the model, and which are generated dynamically according to information from the model’s own fields or from elsewhere. For example a field that classifies an object according to its ratings.

To create such a field we add the field name to list_display (to tell the admin to display it) and create a method with the same name, this method receives the individual object and must return what we want to be displayed on the screen.

# videogameStore/admin.py
class VideogameAdmin(admin.ModelAdmin):
    list_display = ('name', 'created', 'popular')
    # ...

    def popular(self, obj):
        return "Popular" if obj.rating > 4.5 else "No es popular"

Django Admin. dynamic custom fields

Create actions for the Django admin

All models have the delete action available, which allows you to select several rows from the database and delete them.

Delete action in django admin.

In addition to the delete action we can create our own actions that modify our admin elements in the way we wish

As an example we are going to create an action that allows us to set a rating of 5.0 to our objects.

First, we create a function that receives modeladmin, request and the queryset as arguments. The queryset will contain all the objects that we will select in the interface. And we can also add a message to be displayed when the action is executed.

# videogameStore/admin.py
from django.contrib import admin
from django.contrib import messages
from .models import Videogame
# Register your models here.

class VideogameAdmin(admin.ModelAdmin):
    # ...

    def rate_five_stars(modeladmin, request, queryset):
        queryset.update(rating=5.0)
        messages.success(request, "Was rated with 5 stars")

    admin.site.add_action(rate_five_stars, "Add 5 stars rating")

Once the method is created, we add it to the admin through its add_action() method, passing it the method we created and the name we want to appear on the screen to refer to that action, as the first and second arguments, respectively.

Action created in the django admin model

If we select some elements and execute the action, it will rate them with 5 stars and the message we defined will appear.

Success message after executing action in djago admin

Installing external templates for django admin

There are quite a few packages that allow quite sophisticated modifications of django admin, which can even turn it into a CMS, just like Wordpress, with which you can deliver to your customers a fully functional application ready to be used by non-technical people.

Examples of the above include the following packages:

Each one is a topic in itself, so I cannot summarize them in a single entry.

Example of visual enhancement with django material admin

Finally, I will show you an example of visual enhancement with django-material-admin.

Let’s install it.

pip install django-material-admin

And now we modify our INSTALLED_APPS variable

# settings.py
# ...

INSTALLED_APPS = [
    'material',
    'material.admin',
    # removemos django.contrib.admin
    'django.contrib.auth',
    # ...
]

We can add an extra field to our admin models to change the icons, just put the name that appears in the materialize documentation .

# videogameStore/admin.py
from django.contrib import admin
from .models import Videogame

class VideogameAdmin(admin.ModelAdmin):
    # ...
    icon_name = 'gamepad'
admin.site.register(Videogame, VideogameAdmin)

If we now access the admin, we will be able to see a new, much more stylish terminal. And also a more eye-catching administration panel.

admin main screen with django material
Django administration panel with django-material

Log-in screen with django-material
django admin login panel with django-material

I used this package especially because it installs easily and gives a completely different look to the admin. But there are many other options available that you can choose from, some paid and some free.

Security in django admin

It is advisable to change the default url, /admin/, to a less obvious one, this in order to prevent brute force attacks, if the attacker does not know the django admin address, it will be impossible for him to try to guess your password by brute force.

There are also packages that create a fake admin panel that you can monitor, to find out which IP addresses are trying to take over your site via the admin panel, one of them is django-admin-honeypot . Once you identify these IP addresses, you can limit their access, blacklist them or block them completely.

If you need extra functionality for the admin, check the official Django documentation .

Eduardo Zepeda
Web developer and GNU/Linux enthusiast. I believe in choosing the right tool for the job and that simplicity is the ultimate sophistication. Better done than perfect. I also believe in the goodness of cryptocurrencies outside of monetary speculation.
Read more