6. Django Admin Backend
Django’s admin interface is a powerful, built-in tool that allows developers to manage and interact with their application’s data through a web-based UI. It is highly customizable and provides features such as listing, filtering, and modifying data records.
1. Admin is at site level
1.1 How Django Admin Works Across Apps
-
Project-Level Administration:
- The Django admin site is registered at the project level (
admin.site
). - It can manage models from multiple apps in the same admin panel.
- Example: If your project has
blog
,store
, andusers
apps, the admin panel can be used to manage all their models.
- The Django admin site is registered at the project level (
-
App-Level Management:
- Each app defines its own models.
- Developers need to register the models of each app in the respective
admin.py
file. - Example:
blog/admin.py
→ RegistersPost
andComment
models.store/admin.py
→ RegistersProduct
andOrder
models.
- Once registered, all models appear under the same admin interface.
1.2 Is Django Admin the Backend of the Project?
No, Django Admin is just a tool for database management. The actual backend of your project is the Django application itself, which includes:
- Views (for handling HTTP requests)
- Models (for database structure)
- APIs (if using Django REST Framework)
- Business Logic (for processing user actions)
1.3 Can You Use Django Admin as the Only Backend?
While Django Admin allows you to manage data, it is not meant to be used as the main backend for users. It lacks:
- Authentication & Permissions for end users (only admins can access it).
- API functionality (you’d need Django REST Framework for APIs).
- Frontend flexibility (Django Admin is for internal use, not for users).
2. Working with Admin
2.1 Setting Up Django Admin
By default, Django provides an admin interface when you create a project.
Step 1: Create a Django Project
django-admin startproject myprojectcd myprojectpython manage.py migratepython manage.py createsuperuser
You’ll be prompted to enter a username, email, and password.
Step 2: Run the Development Server
python manage.py runserver
Now, visit http://127.0.0.1:8000/admin/ and log in using the superuser credentials.
2.2 Registering Models in Django Admin
To manage database records via the admin panel, you need to register your models.
Step 1: Create a Model in models.py
**
from django.db import models
class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=100) published_date = models.DateField() price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self): return self.title
Step 2: Register the Model in admin.py
**
from django.contrib import adminfrom .models import Book
admin.site.register(Book)
This allows the Book
model to appear in the Django Admin panel.
2.3 Customizing Django Admin
Instead of using admin.site.register(Model)
, you can customize the admin panel using the ModelAdmin
class.
class BookAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'published_date', 'price') search_fields = ('title', 'author') list_filter = ('published_date',) ordering = ('published_date',) list_editable = ('price',)
admin.site.register(Book, BookAdmin)
Features Explained:**
list_display
: Defines which fields are shown in the list view.search_fields
: Enables a search box for filtering records.list_filter
: Adds a filter sidebar to narrow down results.ordering
: Sorts records by a specified field.list_editable
: Allows inline editing of specified fields.
3.4 Adding Actions in Django Admin
Django Admin allows you to define actions that can be applied to multiple records at once.
Step 1: Define an Action in admin.py
**
def mark_books_as_published(modeladmin, request, queryset): queryset.update(published_date="2024-01-01")
mark_books_as_published.short_description = "Mark selected books as published"
class BookAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'published_date', 'price') actions = [mark_books_as_published]
admin.site.register(Book, BookAdmin)
5. Customizing Forms in Django Admin
You can override the default admin form to add validation or customization.
Using ModelForm
in Admin**
from django import forms
class BookAdminForm(forms.ModelForm): class Meta: model = Book fields = '__all__'
def clean_price(self): price = self.cleaned_data.get('price') if price < 0: raise forms.ValidationError("Price cannot be negative") return price
class BookAdmin(admin.ModelAdmin): form = BookAdminForm
admin.site.register(Book, BookAdmin)
Why Customize Forms?
- To validate data before saving.
- To add custom error messages.
- To modify the behavior of form fields.
6. Inlines in Django Admin
If you have related models, you can use inlines to edit them on the same page.
Example:**
class Author(models.Model): name = models.CharField(max_length=100)
class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(Author, on_delete=models.CASCADE)
class BookInline(admin.TabularInline): # or admin.StackedInline model = Book extra = 1
class AuthorAdmin(admin.ModelAdmin): inlines = [BookInline]
admin.site.register(Author, AuthorAdmin)
Why Use Inlines?**
- To manage related objects from a single admin page.
- To provide a better user experience.
7. Overriding Django Admin Templates
If you want to customize the look of the admin panel, you can override its templates.
- Create a directory
templates/admin/
- Copy and modify
base_site.html
{% extends "admin/base.html" %}{% block title %}Custom Admin{% endblock %}{% block branding %}<h1>My Custom Admin</h1>{% endblock %}