Unlocking the Power of Django Admin

Introduction

The Django admin application stands as a powerful tool within the Django framework, designed to streamline data management within your web applications. The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data. The admin application can also be useful for managing data in production, depending on the type of website. After registering the models, we'll show how to create a new "superuser", login to the site, and create some books and authors. These will be useful for testing the views and templates

Setup Django Project: Make sure you have Django installed. If not, you can install it via pip.

pip install django

Create a Django Project: If you haven't already, create a Django project using the Django-admin command.

django-admin startproject myproject

Create an App: Within your Django project, create an app where you will define your models.

cd myproject
python manage.py startapp myapp

Define Models

Creating models in Django involves defining Python classes that represent the data structure of your application. These models will map to database tables when you run Django's migrations. Here's a step-by-step guide on how to create models in Django. In the models.py file of your app (myapp/models.py), define your models using Python classes.

For example

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    publication_date = models.DateField()

    def __str__(self):
        return self.title

The provided code defines two Django models: Author and Book. The Author model includes fields for the author's name and email address. The Book model contains fields for the book's title, publication date, and a ForeignKey linking it to an Author. This establishes a relationship where each book is associated with one author. The __str__ method is overridden in both models to provide a string representation, returning the author's name for Author objects and the book's title for Book objects. These models offer a foundation for storing information about authors and their books within a Django application. The ForeignKey relationship facilitates navigation between related objects, allowing for efficient querying and management of data. This structure adheres to Django's model-centric approach, enabling seamless integration with the Django Admin interface for data management tasks. Its primary function revolves around leveraging your defined models to construct a site area automatically. This area becomes a centralized hub where you can effortlessly create, view, update, and delete records, thereby significantly reducing the time and effort required during development.

Register Models

To make Django aware of your models, you need to register them in the admin.py file of your app (myapp/admin.py). This allows you to manage your models via the Django admin interface.

from django.contrib import admin
from .models import Author, Book

admin.site.register(Author)
admin.site.register(Book)

Run Migrations: Before using your models, you need to create database tables for them. Run the following commands.

python manage.py makemigrations
python manage.py migrate

Interact with Models: Now you can use your models in views, and templates, or manage them via the Django admin interface.

Creating a superuser

We need a user account with Staff status enabled to log into the admin site. To view and create records we also need this user to have permission to manage all our objects. You can create a "superuser" account that has full access to the site and all needed permissions using manage.py.

Call the following command in the same directory as manage.py to create the superuser. You will be prompted to enter a username, email address, and strong password.

python3 manage.py createsuperuser

Once this command completes a new superuser will have been added to the database. Now restart the development server so we can test the login.

python3 manage.py runserver

Logging in and using the site

To login to the site, open the /admin URL (e.g. http://127.0.0.1:8000/admin) and enter your new superuser userid and password credentials (you'll be redirected to the login page, and then back to the /admin URL after you enter your details).

Django Administration

This part of the site displays all our models, grouped by installed application. You can click on a model name to go to a screen that lists all its associated records, and you can further click on those records to edit them. You can also directly click the Add link next to each model to start creating a record of that type.

Django Authentication and authorization

Click on the Add link to the right of Books and Authors to create a new book and author (this will display a dialog much like the one below).

Enter values for the fields. You can create new authors by pressing the + button next to the respective fields (or select existing values from the lists if you've already created them). When you're done, you can press SAVE, Save and add another, or Save and continue editing to save the record.

Add author in Django

Add books

When you've finished adding books, click on the Home link in the top bookmark to be taken back to the main admin page. Then click on the Books link to display the current list of books (or on one of the other links to see other model lists). Now that you've added a few books, the list might look similar to the screenshot below.

Django Administration Home

Select book to change

Conclusion

By following this article, you've learned how to set up a Django project, define models, register them with the admin interface, create a superuser, and effectively navigate the admin site. With these capabilities, managing data in your Django applications becomes streamlined and efficient. As you continue to build your project, the admin interface will serve as a powerful tool for data management and validation.


Similar Articles