Django entry practice to achieve a simple library management system

Web development, that is, writing websites, is a major application direction of Django. Django is one of the most popular python web frameworks. Many students want to know about this learning case. Today we will share one with you: using Django to realize the library management system

There is no need to write sql and the front end. Using the Admin and ORM framework provided by Django, you can easily add, delete, modify and query a many to many table relationship.

Development process


Django 3.1.1

python 3.6.12

(django) E:\python_Projects\django_demo>pip show django
Name: Django
Version: 3.1.1
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Author: Django Software Foundation
License: BSD-3-Clause
Location: d:\anaconda3\envs\django\lib\site-packages
Requires: pytz, asgiref, sqlparse

(django) E:\python_Projects\django_demo>python -V
Python 3.6.12 :: Anaconda, Inc.

django installation:

pip install Django -i

-i   Specify the image source for faster download.

Specify the download version of Django (3.1.1 can be changed to the version you want):

pip install Django==3.1.1 -i

Create project and APP

django-admin startproject booktest
cd booktest
django-admin startapp book_managerment

With path Demo:

(django) E:\python_Projects\django_demo>django-admin startproject booktest
(django) E:\python_Projects\django_demo>cd booktest
(django) E:\python_Projects\django_demo\booktest>django-admin startapp book_managerment

Post operation directory structure:

Install application

Found installed in booktest\booktest\settings.py_ The item "apps" is revised as follows:


design a model

Table structure:

Book table: title, price, pub_date, publish (foreign key, many to one), authors (many to many)

Publish er table: name, city, email

Author table: name, age, au_detail,gender , tel , addr , birthday

The following is the table Association Description:

Modify booktest \ book_ Manager \ Define model classes as follows:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.SmallIntegerField()
    gender_choices = (
        (0, "female"),
        (1, "male"),
        (2, "secrecy"),
    gender = models.SmallIntegerField(choices=gender_choices)
    tel = models.CharField(max_length=32)
    addr = models.CharField(max_length=64)
    birthday = models.DateField()

class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    pub_date = models.DateField()
    publish = models.ForeignKey("Publish", on_delete=models.CASCADE)
    authors = models.ManyToManyField("Author")

class Publish(models.Model):
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=64)
    email = models.EmailField()

Generate local database file

  • Generate migration file: generate statements to create tables based on model classes

  • Perform migration: create tables in the database according to the statements generated in step 1

python makemigrations
python migrate

Files generated after execution:

Insert initial data

After opening the db.sqlite3 file with DataSource, execute the following sql statement:

insert into book_managerment_publish(id, name, city, email)
values (1, "Huashan Publishing House", "Huashan Mountain", ""),
       (2, "Mingjiao Publishing House", "Heimuya", "");

insert into book_managerment_author(id, name, age, gender, tel, addr, birthday)
values (1, "linghu chong", 25, 1, 13432335433, "Huashan Mountain", "1994-5-23"),
       (2, "ren woxing", 58, 1, 13943454554, "Heimuya", "1961-8-13"),
       (3, "Ren yingying", 23, 0, 13878934322, "Heimuya", "1996-5-20");

INSERT INTO book_managerment_book(id, title, price, pub_date, publish_id)
VALUES (1, "Dugu Jiujian", 200, "2019-1-7", 1),
       (2, "Star sucking method", 180, "2019-1-7", 2),
       (3, "Sunflower collection", 280, "2019-3-15", 2);

INSERT INTO book_managerment_book_authors(id, book_id, author_id)
VALUES (1, 1, 1),
       (2, 1, 2),
       (3, 2, 2);

back-stage management

Management interface localization:

  • Localize the language and time and use local habits. Localization is localized in China. Chinese mainland uses simplified Chinese. Time zone uses Asian / Shanghai time zone. Note that Beijing time zone is not used here.

  • Open the booktest/booktest/ file, find the setting items of language code and time zone, and change the content as follows:

TIME_ZONE = 'Asia/Shanghai'

Create administrator:

python createsuperuser

(I set the user name and password to admin)

(django) E:\python_Projects\django_demo\booktest>python createsuperuser
 user name (leave blank to use 'think'): admin
 e-mail address:
Password (again):
Password with user name It's so similar.
Password length is too short. The password must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

Register model class

Open the booktest\booktest\ file and write the following code

from django.contrib import admin
from .models import *

class BookModal(admin.StackedInline):
    model = Book

class PublishAdmin(admin.ModelAdmin):
    inlines = [BookModal]
    list_display = ('id', 'name', 'city', 'email', 'books')
    fields = ('name', 'city', 'email')
    list_filter = ['city']
    search_fields = ['name', 'city']

    def books(self, obj):
        return [book.title for book in obj.book_set.all()]

class BookAdmin(admin.ModelAdmin):
    list_display = ('id', 'title', 'price', 'pub_date', "publish_name", "author")
    fields = ('title', 'price', 'pub_date', "authors")
    search_fields = ['title', 'price', 'pub_date']

    def author(self, obj):
        return [ for author in obj.authors.all()]

    def publish_name(self, obj):

    filter_horizontal = ('authors',)

class AuthorAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'age', 'gender', 'tel', 'addr', 'birthday', 'books')
    fields = ('name', 'age', 'gender', 'tel', 'addr', 'birthday')
    list_filter = ['gender']
    search_fields = ['name', 'age', 'gender', 'tel', 'addr', 'birthday']

    def books(self, obj):
        return [book.title for book in obj.book_set.all()]

Custom management page template

Modify DIRS of TEMPLATES in booktest/booktest/ to the specified path:

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / "templates"],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [

Create the directory booktest/templates/admin, and install the python installation path to Lib \ site packages \ Django \ contrib \ admin \ templates \ admin under base_ Copy the site.html file to this directory and modify it:

Amend to read as follows:

{% extends "admin/base.html" %}

{% block title %}Library background management system{% endblock %}

{% block branding %}
    <h1 id="site-name"><a href="{% url 'admin:index' %}">Library background management system</a></h1>
{% endblock %}

{% block nav-global %}{% endblock %}

Start project

After executing the following command:

python runserver


Operation demonstration

Search for books written by all authors:

Query the publisher and author of each book:

Check the books published by each publishing house:

Modify author information:

Modify the book information to manage the author:

Modify the press information to manage each book published:

Support search and filtering:

The above is the development process of the whole library management system.

Tags: Python Django Back-end

Posted on Tue, 07 Dec 2021 00:46:19 -0500 by herod1