Django 5.2.3 构建的图书管理系统

Django 5.2.3 构建的图书管理系统

下面是一个使用 Django 5.2.3 构建的图书管理系统实现方案,包含模型设计、后台管理、基本视图和模板:

1. 环境准备

安装部分请先看

Django 5 学习笔记总纲-CSDN博客 安装部分

复制代码
pip install django==5.2.3
django-admin startproject library
cd library
python manage.py startapp books

2. 模型设计 (`books/models.py`)

复制代码
from django.db import models
from django.urls import reverse

class Author(models.Model):
    name = models.CharField(max_length=100)
    birth_date = models.DateField(null=True, blank=True)
    bio = models.TextField(blank=True)
    
    def __str__(self):
        return self.name
    
    def get_absolute_url(self):
        return reverse('author_detail', args=[str(self.id)])

class Book(models.Model):
    GENRE_CHOICES = [
        ('FIC', '小说'),
        ('SCI', '科幻'),
        ('HOR', '恐怖'),
        ('HIS', '历史'),
        ('BIO', '传记'),
    ]
    
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
    isbn = models.CharField('ISBN', max_length=13, unique=True)
    genre = models.CharField(max_length=3, choices=GENRE_CHOICES)
    publish_date = models.DateField()
    stock = models.PositiveIntegerField(default=0)
    description = models.TextField(blank=True)
    
    def __str__(self):
        return f"{self.title} ({self.author.name})"
    
    def get_absolute_url(self):
        return reverse('book_detail', args=[str(self.id)])

3. 后台管理配置 (`books/admin.py`)

复制代码
from django.contrib import admin
from .models import Author, Book

@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
    list_display = ('name', 'birth_date')
    search_fields = ('name',)
    date_hierarchy = 'birth_date'

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'genre', 'stock')
    list_filter = ('genre', 'publish_date')
    search_fields = ('title', 'isbn', 'author__name')
    raw_id_fields = ('author',)
    date_hierarchy = 'publish_date'
    ordering = ('-publish_date',)

4. URL 配置 (`library/urls.py`)

4.1urls.py

复制代码
from django.contrib import admin
from django.urls import path, include
from books import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('books/', include('books.urls')),
]

4.2创建 `books/urls.py`

复制代码
from django.urls import path
from . import views

urlpatterns = [
    path('', views.BookListView.as_view(), name='book_list'),
    path('<int:pk>/', views.BookDetailView.as_view(), name='book_detail'),
    path('authors/', views.AuthorListView.as_view(), name='author_list'),
    path('authors/<int:pk>/', views.AuthorDetailView.as_view(), name='author_detail'),
]

5. 视图实现 (`books/views.py`)

复制代码
```python
from django.views.generic import ListView, DetailView
from .models import Book, Author

class BookListView(ListView):
    model = Book
    template_name = 'books/book_list.html'
    context_object_name = 'books'
    paginate_by = 10
    
    def get_queryset(self):
        queryset = super().get_queryset()
        # 添加搜索功能
        if 'search' in self.request.GET:
            search_term = self.request.GET['search']
            queryset = queryset.filter(title__icontains=search_term)
        return queryset

class BookDetailView(DetailView):
    model = Book
    template_name = 'books/book_detail.html'

class AuthorListView(ListView):
    model = Author
    template_name = 'books/author_list.html'
    context_object_name = 'authors'

class AuthorDetailView(DetailView):
    model = Author
    template_name = 'books/author_detail.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['books'] = self.object.books.all()
        return context
```

6. 模板文件

`templates/books/book_list.html`:

复制代码
<!DOCTYPE html>
<html>
<head>
    <title>图书列表</title>
</head>
<body>
    <h1>图书管理系统</h1>
    <form method="get">
        <input type="text" name="search" placeholder="搜索书名...">
        <button type="submit">搜索</button>
    </form>
    
    <ul>
        {% for book in books %}
            <li>
                <a href="{{ book.get_absolute_url }}">{{ book.title }}</a>
                ({{ book.author.name }}) - 库存: {{ book.stock }}
            </li>
        {% endfor %}
    </ul>
    
    {% include "pagination.html" %}
</body>
</html>

templates/books/book_detail.html

复制代码
<!DOCTYPE html>
<html>
<head>
    <title>{{ book.title }}</title>
</head>
<body>
    <h1>{{ book.title }}</h1>
    <p>Author: {{ book.author }}</p>
    <p>Publication date: {{ book.publication_date }}</p>
</body>
</html>
相关推荐
程序设计实验室6 天前
分享一些2026年有意思的现代化Django生态组件
django
程序设计实验室7 天前
当人人都能用 AI 写代码时,我为什么选择重回 Django?
django·djangostarter
markfeng812 天前
Python+Django+H5+MySQL项目搭建
python·django
QQ40220549613 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
百锦再13 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
starlaky13 天前
Django入门笔记
笔记·django
QQ51100828513 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
WeiXin_DZbishe13 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5
B站计算机毕业设计超人13 天前
计算机毕业设计Django+Vue.js高考推荐系统 高考可视化 大数据毕业设计(源码+LW文档+PPT+详细讲解)
大数据·vue.js·hadoop·django·毕业设计·课程设计·推荐算法
计算机程序猿学长13 天前
大数据毕业设计-基于django的音乐网站数据分析管理系统的设计与实现(源码+LW+部署文档+全bao+远程调试+代码讲解等)
大数据·django·课程设计