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>
相关推荐
玄同76539 分钟前
SQLite + LLM:大模型应用落地的轻量级数据存储方案
jvm·数据库·人工智能·python·语言模型·sqlite·知识图谱
ggabb3 小时前
中文的精确与意境,从来都不是英文能比肩的
sqlite
玄同7653 小时前
Python 后端三剑客:FastAPI/Flask/Django 对比与 LLM 开发选型指南
人工智能·python·机器学习·自然语言处理·django·flask·fastapi
B站_计算机毕业设计之家4 小时前
豆瓣电影推荐系统 | Python Django Echarts构建个性化影视推荐平台 大数据 毕业设计源码 (建议收藏)✅
大数据·python·机器学习·django·毕业设计·echarts·推荐算法
orange_tt16 小时前
Djiango配置Celery
数据库·sqlite
luoluoal20 小时前
基于深度学习的web端多格式纠错系统(源码+文档)
python·mysql·django·毕业设计·源码
Ronin3051 天前
日志打印和实用 Helper 工具
数据库·sqlite·rabbitmq·文件操作·uuid生成
wxin_VXbishe1 天前
springboot旅游信息管理系统-计算机毕业设计源码21675
java·c++·spring boot·python·spring·django·php
云和数据.ChenGuang1 天前
python 面向对象基础入门
开发语言·前端·python·django·flask
墨染青竹梦悠然2 天前
基于Django+React的个人财务管理系统
python·django·毕业设计