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>
相关推荐
程序媛徐师姐2 小时前
Python基于Django的小区果蔬预定系统【附源码、文档说明】
python·django·小区果蔬预定系统·果蔬预定·python小区果蔬预定系统·小区果蔬预定·python果蔬预定系统
Azhao110620 小时前
商城产品详情页的客服咨询在哪里设置详解:从入门到实战全攻略
sqlite
码界筑梦坊1 天前
111-基于Python的中国旅游用户数据可视化分析系统
python·信息可视化·django·毕业设计·旅游
YJlio1 天前
10.2.8 以其他账户运行服务(Running services in alternate accounts):为什么“把服务切到某个用户账号下运行”,本质上是在改变服务的整个安全上下文?
python·安全·ios·机器人·django·iphone·7-zip
小熊Coding1 天前
懂车帝汽车销售数据可视化分析系统
python·信息可视化·django·汽车·数据可视化分析·懂车帝·汽车销售数据分析
ggabb1 天前
战斗机器人的发展与战争伦理影响
sqlite
鹏子训2 天前
AI记忆新思路:用SQLite替代向量数据库,去EMBEDDINGS化,谷歌开源Google Always On Memory Agent
数据库·人工智能·sqlite·embedding
ma_de_hao_mei_le2 天前
ntquerysystemiunfomation 数据传递
django
Muyuan19982 天前
22.让 RAG Agent 更像真实产品:聊天页面优化、PDF 上传、知识库重建与检索片段展示
python·django·pdf·fastapi
Muyuan19982 天前
25.Paper RAG Agent 优化记录:上传反馈、计算器安全与 Chunk 参数调整
python·安全·django·sqlite·fastapi