Django Admin Hands-On
Django Admin Hands-On
and books in your Django project. You can extend them further by adding additional
fields as needed.
models.py
from django.db import models
class Author(models.Model):
salutation = models.CharField(max_length=10) # Mr., Ms., etc.
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
def __str__(self):
return f"{self.salutation} {self.first_name} {self.last_name}"
class Publisher(models.Model):
name = models.CharField(max_length=200)
address = models.CharField(max_length=200)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30, blank=True) # Optional
country = models.CharField(max_length=50)
website = models.URLField(blank=True) # Optional
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=255)
publication_date = models.DateField()
num_pages = models.IntegerField(blank=True, null=True) # Optional
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
authors = models.ManyToManyField(Author)
def __str__(self):
return self.title
Run Migrations:
python manage.py makemigrations
python manage.py migrate
Manually populate your Django database with sample data:
Python manage.py shell
Author Model:
from .models import Author # Assuming models.py is in the same app directory
author1 = Author.objects.create(
salutation="Mr.",
first_name="John",
last_name="Doe",
email="johndoe@example.com",
)
author2 = Author.objects.create(
salutation="Ms.",
first_name="Jane",
last_name="Smith",
email="janesmith@example.com",
)
Publisher Model:
publisher1 = Publisher.objects.create(
name="Big Publishing House",
address="123 Main Street",
city="New York",
state_province="NY",
country="USA",
website="https://www.bigpublishinghouse.com",
)
publisher2 = Publisher.objects.create(
name="Small Press",
address="456 Elm Street",
city="Chicago",
state_province="IL",
country="USA",
website="https://www.smallpress.com",
)
Book Model:
admin.py:
from django.contrib import admin
admin.site.register(Author)
admin.site.register(Publisher)
# admin.site.register(Book)
from .models import Author, Publisher, Book
admin.site.register(Author)
admin.site.register(Publisher)
# admin.site.register(Book)
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publisher', 'publication_date')
ordering = ('-publication_date',)
search_fields = ('title',)
SuperUser Creation
python3 manage.py createsuperuser
Username: Provide Username
Email address: Provide Email Address
Password: Provide Password
Password (again): Type the password again
Superuser created successfully.
The “Recent Actions” panel in Django Admin displays LogEntry models. To clear
it you would just delete all the objects: