Build a Full‑Featured Django Library Management System from Scratch

This tutorial walks you through creating a real‑world Django project, covering template, static, and middleware settings, switching to MySQL, defining models with one‑to‑many and many‑to‑many relationships, implementing CRUD views, configuring URLs, and building simple HTML templates with code examples and key configuration screenshots.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Build a Full‑Featured Django Library Management System from Scratch

Django File Configuration

Django template configuration

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "template")],  # template folder location
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Django static files configuration

STATIC_URL = '/static/'  # prefix used in HTML
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),  # static files location
]

Middleware configuration

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',  # temporarily disabled for testing
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Django Database Configuration

Django uses SQLite by default, but this tutorial switches to MySQL to match the development environment. After creating a MySQL database, update settings.py as follows:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test_site',
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'USER': 'root',
        'PASSWORD': '',  # leave empty if no password
    }
}

In the same directory, modify __init__.py to enable MySQL support:

import pymysql
pymysql.install_as_MySQLdb()

Essential Django Views

HttpResponse – returning raw data to the browser

def index(request):
    # business logic
    return HttpResponse("Hello World")

render – filling a template with context data

def index(request):
    # business logic
    return render(request, "index.html", {"name": "Albert", "hobby": ["音乐", "篮球"]})

redirect – sending the client to another URL

def index(request):
    # business logic
    return redirect("/home/")

By default redirect() issues a 302 temporary redirect; add permanent=True for a 301 permanent redirect.

Django Library Management System

Goal: create pages for publishers, books, and authors, with one‑to‑many (publisher‑book) and many‑to‑many (author‑book) relationships.

Start a project and an app:

# django-admin startproject lms
# cd lms
# python3 manage.py startapp app01

Create a MySQL database named test_site (or any name you prefer).

Update settings.py with the template, static, database, and middleware settings shown above. During early testing you may temporarily comment out the CSRF middleware.

Define models in app01/models.py:

class Publisher(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=64)

class Book(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=64)
    publisher = models.ForeignKey(to=Publisher)

class Author(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=64)
    book = models.ManyToManyField(to=Book)

Implement CRUD view functions in app01/views.py (publishers, books, authors). Example for listing publishers:

def publisher_list(request):
    publisher = models.Publisher.objects.all()
    return render(request, 'publisher_list.html', {'publisher_list': publisher})

Similar functions are provided for adding, editing, and deleting each entity, using request.method == 'POST' for form submissions and redirect() after successful operations.

Map URLs in lms/urls.py to the view functions:

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^publisher_list/', views.publisher_list),
    url(r'^add_publisher/', views.add_publisher),
    url(r'^drop_publisher/', views.drop_publisher),
    url(r'^edit_publisher/', views.edit_publisher),
    url(r'^book_list/', views.book_list),
    url(r'^add_book/', views.add_book),
    url(r'^drop_book/', views.drop_book),
    url(r'^edit_book/', views.edit_book),
    url(r'^author_list/', views.author_list),
    url(r'^add_author/', views.add_author),
    url(r'^drop_author/', views.drop_author),
    url(r'^edit_author/', views.edit_author),
    url(r'^$', views.publisher_list),
]

Create simple HTML templates that iterate over the querysets using Django’s {% for %} syntax. Example for displaying publishers:

<tbody>
{% for publisher in publisher_list %}
    <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ publisher.name }}</td>
        <td class="text-center">
            <a class="btn btn-info btn-sm" href="/edit_publisher/?id={{ publisher.id }}"><i class="fa fa-pencil fa-fw" aria-hidden="true"></i>编辑</a>
            <a class="btn btn-danger btn-sm" href="/drop_publisher/?id={{ publisher.id }}"><i class="fa fa-trash-o fa-fw" aria-hidden="true"></i>删除</a>
        </td>
    </tr>
{% endfor %}
</tbody>

The same pattern applies to books and authors, with additional <select> elements for choosing related publishers or books.

The complete source code is available on GitHub at https://github.com/mayite/lms .

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DjangoORMWeb DevelopmentCRUD
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.