Django Tutorial Part 5: Working with Django Admin Site

Disclaimer: Your support helps keep JovialGuide running! Our content is reader-supported. This means if you click on some of our links, we may earn a commission.

Django comes with a built-in interactive admin site which allows you perform Create, Read, Update and Delete (CRUD) operations on Django models. This admin site makes managing database records and performing CRUD operations a lot easier and faster without writing any database queries.

In this complete beginners guide to Django part 5, we will show you how to create a superuser account, how to login to the Django admin site and how to work with the Django admin site. This is a complete beginners guide to Django, so if you haven’t read the previous part (part 4), then see part 4: creating models or see part 1 – introduction to Django to get started.

What is the Django Admin Site?

The Django admin site is an administrative interface that is built into Django for managing model records. It comes with an interface for Creating, Reading, Updating and Deleting model records without the need to write a query to the model. Django admin site is similar to phpMyAdmin, except that you can’t write SQL queries to perform an operation. phpMyAdmin supports writing queries while Django admin site doesn’t!

The Django admin site is a developer administrative interface to quickly manage model records. It is a developer administrative interface, which means that you will need a superuser account to be able to access it. The Django admin site is not intended for users or clients, but for developers alone. For this reason, anybody who has access to the Django admin site can Create, Read, Update and Delete the records in the models. Since it is intended for developers and not users, it is highly recommended you create a special user interface for your users or clients to manage records.

Django admin site should be hidden from non-authorized users since when accessed with a superuser privilege, one can easily manipulate the records in the model, by Creating, Reading, Updating and even Deleting a record without any form of retrieval or backup!

Registering a Django Model

So, for us to perform CRUD operations on the models we created using the Django admin site, we will have to register it. The concept of registering a Django model is to be able to perform CRUD operations on it directly in the Django admin site. This basically means that each model (table) we create has to be registered if we want to use it in the Django admin site.

To register a Django model, copy and paste the following lines of code in django_project/blog/admin.py:

from blog.models import Article, Category

admin.site.register(Article)
admin.site.register(Category)
  • Notice that we imported the models that we created. So, for every model you want to register, always import!

Creating a SuperUser Account

Since the Django admin site is an administrative panel where data is stored (like a database), then we need an account with a superuser privilege to access it. Django comes with a createsuperuser command that allows us easily create a superuser account.

To create a superuser in Django, run the following command (if your development server is still running, press ctrl + c to stop it):

  python manage.py createsuperuser
  • Enter your username, email address, and a strong password for the superuser account

If you see:

Superuser created successfully.

Then you have created a superuser account.

Logging-in to the Django Admin Site

After you have created a superuser account, run the following command to start the development server:

python manage.py runserver

If you need to specify an alternative port for your Django project, after runserver, specify the port you want to run on. For example; if you want to run your Django project on port 1000, run:

python manage.py runserver 1000
  • Then the server will run on port 1000 like this: http://127.0.0.1:1000/
  • The default development port of Django is 8000

If you check your project’s root urls.py file, you will see:

from django.contrib import admin
from django.urls import path

urlpatterns = [
  path('admin/', admin.site.urls)
]

That is the path to the Django admin site. Open your web browser and navigate to http://127.0.0.1:8000/admin.

You will see something like the screenshot below:

Django Admin Site Login

This is the Django admin site login screen. It requires you to login with the superuser account details you created.

Type the username and password of the superuser account you created earlier and login.

This is what the Django admin site looks like:

Django Admin Site

Creating a Category Object

When you are logged in, you will notice that all of the models are grouped to the blog app you created and registered. If you start another app, create and register models for it, then all of those models will be grouped under the new app.

Django Admin Site Blog Models

  • blog is our app name
  • Articles and Categorys are the blog models we created. They are grouped under blog because we created them in the blog’s models.py file.

Note:

  • We defined the model classes in singular form – Article and Category, but Django is displaying them in plural form. Define your models in singular form then Django will display them in plural forms! Django emphasizes singular model class naming. For example; call it Story instead of Stories, Company instead of Companies and Category instead of Categories.
  • Django is displaying the plural form of the Category model as Categorys instead of Categories. Django would not know the plural form of some words, like those that end with ry, etc. But we can fix this by specifying the plural form of a model to be displayed if we are unhappy with the regular s that Django uses.

To fix this, we will create a Meta class inside the Category model and specify the plural form that we want to be displayed, using the verbose_name_plural property.

Open django_project/blog/models.py, add the following two lines of code above the def __str__(self): method:

class Meta:
  verbose_name_plural = "Categories"

Be sure to fix indentations to avoid IndentationError. After that add an empty line to separate the Meta class from the def __str__(self): method. This is what the Category model class should look like:

class Category(models.Model):

  STATUS_CHOICES = [
    ('unpublished', 'Unpublished'),
    ('published', 'Published')
  ]

  title = models.CharField(max_length=200)
  description = models.TextField()
  status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='unpublished')
  created_at = models.DateTimeField(auto_now_add=True)
  updated_at = models.DateTimeField(auto_now=True)

  # model methods
  def get_absolute_url(self):
    return reverse('category-detail', args=[str(self.id)])

  def get_edit_url(self):
    return reverse('category-edit', args=[str(self.id)])
    
  def get_delete_url(self):
    return reverse('category-delete', args=[str(self.id)])

  def __str__(self):
    return self.title

Once you have done everything without error on the terminal, If your development server is not running, execute:

python manage.py runserver

Open the Django admin site via http://127.0.0.1:8000/admin, you should see Categories instead of Categorys:

Django Admin Site Blog Models Corrected

Since the Article model has a ForeignKey relationship pointing from the category field to the Category model, then we will start by creating a category first (before articles) for our blog. See part 4: creating models for more.

Click on the + Add button to the right of Category to create a category for our articles.

Django Admin Site - Add Category Button

Go ahead and fill the fields and click either:

  • Save and Add Another – To save the Category object then open a fresh form for you to create another Category object
  • Save and Continue Editing – To save the Category object, then allow you continue editing it
  • Save – To save the Category object, then take you to the Category list page after saving

Notice that:

  • We defined a created_at and an updated_at field in the Category model class, but they are not showing for editing. Why? This is because we added auto_now_add=True to the created_at DateTimeField() field, and auto_now=True to the updated_at DateTimeField() field, which means that Django should automatically fill the current date and time to the created_at field when the category is created, and also automatically update the updated_at field with the date and time that the category was last edited. For this reason, Django hides these fields, basically because they are automated.
  • However, setting auto_now=False to the updated_at field, and auto_now_add=False to the created_at field will cause them to appear for editing. This is because they are no more automated by Django. Setting these field options to False is not wise, except we want to enter the values to these fields in the views, or we want to override the save() method to fill these fields for us. For this complete beginners guide to Django, we will set their field options to True so that Django will simply automate them for us.

Please see the previous chapter on creating models to learn more.

You can also add as many categories as you would like, set some category object as published, while some as unpublished.

Django Admin Site - Add Category Page

After you have created the categories that you want, click on Categories on the left side (sidebar) of the Django admin site.

Django Admin Site - Sidebar Categories

You will see all of the categories that you have created.

Django Admin Site - Categories List Page

Note:

  • Notice it is showing the title of the category. This is the work of the magic __str__() model method we defined in the Category model. Remember we returned self.title (title of the category), so it shows the title of the categories here. Imagine if we had not defined the __str__() magic method, then our categories here would show Object (1), Object (2), etc., depending on the number of objects in the Category model.

Editing the Category Object

If you are ready to edit a category, click on it to open the category edit screen.

Django Admin Site - Edit Category

Notice the red delete button by the bottom left. That button allows you delete an object.

Don’t worry about adding articles using the Django admin site, we will do that when we create modelforms in the later chapter.

Customizing the Django Admin Site

The Django admin site is fully customizable. We can customize the Django admin site to suit your needs by adding some other features to it.

To customize the Django admin site, we will be working with the admin.py file in the blog app. Open django_project/blog/admin.py. We will be working with this file a lot!

Adding List Filters to Django Admin Site

As you add more objects, it will begin to become difficult to manage records. So, there will be need to add a filter box which allows you filter or get data based on certain conditions.

Here, we will add what Django calls List Filters. It is a search filter that allows you easily find or filter objects or records based on certain conditions.

Add the following lines of code at the end of the django_project/blog/admin.py file:

class CategoryAdmin(admin.ModelAdmin):

  list_filter = ('created_at', 'updated_at',)
  • The code snippet above adds a filter box by the right side of your Django admin site. The list_filter attribute accepts a tuple of fields you want to display as part of the filters. In our example, we are filtering based on the created_at and the updated_at fields.

Save and visit your categories page in the Django admin site. You should see something like this:

Django Admin Site - Category List Filter

Django Tutorial Series

In this complete beginners guide to Django, we have been able to cover part 1 – part 5. If you need to read them again, or have not read them yet, please see:

In the next complete beginners guide to Django, we will show you:

We hope this complete beginners guide to Django – working with the Django admin site (part 5), helped you learn how to create a superuser account, login to the Django admin site and how to work with the Django admin site. This is a complete beginners guide to Django, so if you haven’t read the previous part (part 4), then see part 4: creating models or see part 1 – introduction to Django to get started.

See other of our Django tutorials for more.

You Might Also Like

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Shares