Skip to main content

Command Palette

Search for a command to run...

How to Use Django Admin and Models: A Beginner's Guide

Published
4 min read
How to Use Django Admin and Models: A Beginner's Guide
R
Backend Engineer with experience building and deploying scalable AI-powered applications for enterprise pharma clients. Strong in designing high-performance APIs and backend systems using Python, FastAPI, and Django, and integrating LLM/RAG pipelines using LangChain, Pinecone, and PostgreSQL for intelligent search and contextual responses. Comfortable working across the full stack of production systems — from database design and authentication (OAuth 2.0 / Microsoft SSO / Okta) to cloud deployment on AWS (EC2, ALB, ECR, S3, Aurora, CloudWatch). Experienced in improving reliability and observability using tools like Langfuse for LLM tracing and Keploy for automated API testing. Passionate about building real-world backend systems that power GenAI products, with a focus on scalability, security, and clean system design.

Previous Related Blog : Getting Started with Django: Basic Setup and Overview

What is Django Admin ?

  • Django Admin is a powerful panel which has built-in interface for managing Django Models. It allows us to quickly perform CRUD (Create, Read, Update, Delete) operations on app data without having to write any custom views or forms.

Django Admin Panel Setup

  • Before using Django Admin, we need to migrate admin features into our project.
python manage.py migrate

  • To access the Django Admin Panel, we need to create a superuser (root user) with a password.

  • To log in to the Admin Panel, go to http://127.0.0.1:8000/admin/ in your browser.

  • Once you enter the correct credentials, you will see the Admin Panel screen.

Project Setup

  • In the core/settings.py file, import the os library. Then, add the media URLs and media root to handle images of products and other media files.
# Below the STATIC_URL  in settings.py, we will define the MEDIA_URL and MEDIA_ROOT to manage media files.
STATIC_URL = 'static/'
STATICFILES_DIRS = ['static/']

MEDIA_URL = '/media/'
# This line tells Django to use the base directory and add a **media** folder. We can then store images in that folder.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
  • Now, we need to import what we created in core/settings.py into core/urls.py. This is necessary to access and allow us to upload images.
from django.contrib import admin # already present
from django.urls import path,include # already present
from . import settings # newly added
from django.conf.urls.static import static # newly added

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('store.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # newly added

What are Models in Django ?

  • A Django model is the built-in feature that Django uses to create tables, their fields and various constraints.

  • A model in Django is a way to represent your data. It defines the essential fields and behaviors for the data you want to store. Typically, each model corresponds to a single database table.

What is a Foreign Key ?

  • Foreign Key is used to create a relationship between two database models, where one model refers to another.

  • It represents a “many-to-one” relationship, meaning multiple records in one table can associated with a single record in another table.

Example : Let’s assume you have two models: Author and Book.
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

    def __str__(self):
        return self.name

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

    def __str__(self):
        return self.title
  1. Here ForeignKey is defined in the Book Model, indicating that each book is associated with one Author.

  2. The on_delete=models.CASCADE argument ensures that when an author is deleted, all related books are also deleted.


  • Let's create a model for our store in store/models.py with four classes: Category, Customer, Product, and Order. These classes will represent the different aspects of our store's data.
from django.db import models
import datetime
# Create your models here.

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

    # The variable named "verbose_name_plural= categories" in meta specifies the plural instance of "category".
    class Meta:
        verbose_name_plural = "categories"

class Customer(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    phone=models.CharField(max_length=10)
    email=models.EmailField(max_length=100)
    password=models.CharField(max_length=100)

    def __str__(self):
        return f"{self.first_name}{self.last_name}"

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(default=0,max_digits=8,decimal_places=2)
    # Foreign Key is used to create a relationship between two tables
    category = models.ForeignKey(Category,on_delete=models.CASCADE,default=1)
    description = models.CharField(max_length=300,default='',null=True,blank=True)
    image = models.ImageField(upload_to='uploads/product/')

    def __str__(self):
        return self.name

class Order(models.Model):
    # `on_delete=models.CASCADE` means that deleting a `Product` will also delete all related `Order` instances, but deleting an `Order` does not affect the `Product`.
    product = models.ForeignKey(Product,on_delete=models.CASCADE)
    customer = models.ForeignKey(Customer,on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)
    address = models.CharField(max_length=100,default='',blank=True)
    phone = models.CharField(max_length=15,default='',blank=True)
    date = models.DateField(default=datetime.datetime.today)
    status = models.BooleanField(default=False)

    def __str__(self):
        return self.product

🚫
If this error occurs while making migrations of models…. install “pillow“.
pip install pillow
  • Now, we will create the migrations for the models we have defined.
python manage.py makemigrations
python manage.py migrate

  • To see the changes we made to the models in the Django admin panel, we need to register our models in admin.py.
from django.contrib import admin
from .models import Category,Customer,Product,Order
# Register your models here.

admin.site.register(Category)
admin.site.register(Customer)
admin.site.register(Product)
admin.site.register(Order)
  • Now, we can see the models of our application in the admin interface.

  • We can also verify that the fields we created in each class are now available.


Connect with me :

More from this blog

Backend

8 posts

This page will have all content related to backend engineering.