Django Admin (Registering Models, Customizing Admin Site)

Django Admin (Registering Models, Customizing Admin Site)

ยท

5 min read

Django under the hood provides an app called Admin a.k.a Django Admin, which provides Admin UI interface/web page for your Django Project. This admin interface can automatically generate CRUD views/ (form/tables) for your models with very minimal setup i.e (Registering your models to admin)

This Admin app is usually said to be one of the most powerful parts of Django

Let's deep to use Django Admin on our projects

Using Django Admin/ Registering Models

  1. Creating a test Model named Information

     # inside your models.py file
     from django.db import models
    
     class Information(models.Model):
         name = models.CharField(max_length=100)
         date_of_birth = models.DateField()
         salary = models.IntegerField()
    

    Don't forget to create migrations and then migrate

  2. Registering your models to Django Admin

    • Open up admin.py file that exists in your app (when you create django app through manage.py startapp [app] command, you will automatically get this file along other files like models.py that we have been using)
    • To let Django Admin work for our models, we simply register our model class on this admin.py file, by using admin.site.register()

      from django.contrib import admin
      
      from .models import Information  # import your model
      
      admin.site.register(Information) # actual registration
      
  3. Create Superuser to login to Django Admin

    • Because Django also contains a built in Auth/User app which we can use to manage users and authentication, we can easily use this to create our superuser/login mechanism and everything works like a magic
    • You can always create a new User app and authentication process, but we will leave that for another tutorial
    • On your shell, run python manage.py createsuperuser command
    • This command will ask bunch of questions to fill up the User table with attributes is_staff and is_superuser set to True. This, attributes are the table columns
    • Django admin/UI login requires is_staff or is_superuser set to True for authorization
    • Which means, anyone, any user on our project can initiate login to the admin site but won't get access since other users is_staff and is_superuser are set to False

      -> python manage.py createsuperuser
      Username (leave blank to use 'djangotherightway'): admin
      Email address: admin@example.com
      Password: 
      Password (again): 
      Superuser created successfully.
      
  4. login to Django Admin Site

    • So, we completed our core process for working out with Django Admin, we now need a URL through which we can access our Admin Site
    • Register Admin urls to our urls.py

      from django.contrib import admin
      from django.urls import path
      
      urlpatterns = [
        path('admin/', admin.site.urls),
      ]
      
    • Now, we can access our admin site through /admin/ url
    • I suggest to change this from /admin/ to something unguessable, so as to prevent users from bruteforcing this page or accessing this page. In production environment, i usually disable this url path

      By default, when creating a project using django-admin startproject [project] command, Django will automatically do this for us

    • Run your Django server using python manage.py runserver and navigate to /admin/ djangotherightway-django-admin-login-page.png

    • Now, login using the credentials we just created on Step-3, and you will be able to see the model we registered on Step-2 djangotherightway-django-admin-home-page.png

    • You can now, perform CRUD operations to your models, like add a new object/row, view all objects/rows, update and delete

      You may see that Groups and Users models are already registered on Django admin through we didn't do it manually. This is because this Auth app has already registered those models on its admin.py file. You can see the code on github here

Customizing Django Admin Site

Django admin site is super customizable, but we will see some basics so that you can get some idea about its customizations.

Customizing Admin view for models can be done through admin.ModelAdmin class. We basically create a class using/subclassing admin.ModelAdmin and then tell Django admin to use this custom ModelAdmin while registering a model

  • Customize Table display field

    • When you see the table page for your models like from the above example, you will see something like this (assuming you have created two records/objects) a.png
    • This table view doesn't look nice, so lets add some columns/fields on this table view using list_display attributes on admin.ModelAdmin

        # on your admin.py 
        from django.contrib import admin
        from .models import Information
      
        class InformationAdmin(admin.ModelAdmin):
            list_display = ('name', 'date_of_birth', 'salary')
      
        admin.site.register(Information, InformationAdmin)
      
    • Now, save the changes and run your server, you will see the table now has name, date_of_birth and salary fields
    • django-admin1.png
  • Add custom fields to table List Display

    • Let's create up age field obtained from date_of_birth and display it on the list display table fields

        from django.contrib import admin
        from .models import Information
      
        class InformationAdmin(admin.ModelAdmin):
            list_display = ('name', 'date_of_birth', 'salary', 'age')
      
            @admin.display()
            def age(self, obj):
                # this is rough implementation of finding
                # out age from date of birth, so as to keep
                # this example as easy as possible
                from datetime import datetime
                current_year = datetime.today().year
                born_year = obj.date_of_birth.year
                return current_year - born_year
      
    • Screen Shot 2022-04-02 at 12.02.42.png
  • Adding filters

    • We can use list_filters attribute to set filter fields

        from django.contrib import admin
        from .models import Information
      
        class InformationAdmin(admin.ModelAdmin):
            list_filters=['date_of_birth']
      
        admin.site.register(Information,InformationAdmin)
      
    • django-admin-filters.png

These were all basics things that we can do with Django Admin interface, but there are much more advance customizations available to use.

If i should write more on advanced Customization, let me know in comments.