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>
相关推荐
二等饼干~za89866820 小时前
碰一碰发视频系统源码开发搭建--技术分享
java·运维·服务器·重构·django·php·音视频
高洁011 天前
基于Tensorflow库的RNN模型预测实战
人工智能·python·算法·机器学习·django
luoluoal2 天前
基于python的RSA算法的数字签名生成软件(源码+文档)
python·mysql·django·毕业设计
牢七3 天前
5655869
django
秋氘渔4 天前
智演沙盘 —— 基于大模型的智能面试评估系统
python·mysql·django·drf
Java Fans4 天前
PyQt实现SQLite数据库操作案例详解
数据库·sqlite·pyqt
jcsx5 天前
如何将django项目发布为https
python·https·django
百锦再5 天前
京东云鼎入驻方案解读——通往协同的“高架桥”与“快速路”
android·java·python·rust·django·restful·京东云
jzlhll1235 天前
关系型数据库Sqlite常用知识点和androidROOM
sqlite·androidroom
Warren985 天前
datagrip新建oracle连接教程
数据库·windows·云原生·oracle·容器·kubernetes·django