django 写图书管理系统
时间: 2023-11-11 19:05:47 浏览: 86
以下是一个简单的基于 Django 的图书管理系统的实现示例:
1. 创建 Django 项目和应用程序:
```
$ django-admin startproject library
$ cd library
$ python manage.py startapp books
```
2. 在 `books` 应用程序中创建模型:
```python
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
published_date = models.DateField()
isbn = models.CharField(max_length=13)
cover_image = models.ImageField(upload_to='covers/', null=True, blank=True)
def __str__(self):
return self.title
```
3. 在 `books` 应用程序中创建视图:
```python
from django.shortcuts import render, get_object_or_404
from .models import Book
def book_list(request):
books = Book.objects.all()
return render(request, 'book_list.html', {'books': books})
def book_detail(request, pk):
book = get_object_or_404(Book, pk=pk)
return render(request, 'book_detail.html', {'book': book})
```
4. 在 `books` 应用程序中创建模板:
`book_list.html`
```html
{% extends 'base.html' %}
{% block content %}
<h1>Book List</h1>
{% for book in books %}
<div class="book">
<img src="{{ book.cover_image.url }}" alt="{{ book.title }}">
<h2>{{ book.title }}</h2>
<p>Author: {{ book.author }}</p>
<p>Published: {{ book.published_date }}</p>
<p>ISBN: {{ book.isbn }}</p>
<a href="{% url 'book_detail' pk=book.pk %}">View Details</a>
</div>
{% endfor %}
{% endblock %}
```
`book_detail.html`
```html
{% extends 'base.html' %}
{% block content %}
<h1>{{ book.title }}</h1>
<div class="book">
<img src="{{ book.cover_image.url }}" alt="{{ book.title }}">
<p>Author: {{ book.author }}</p>
<p>Published: {{ book.published_date }}</p>
<p>ISBN: {{ book.isbn }}</p>
</div>
<a href="{% url 'book_list' %}">Back to List</a>
{% endblock %}
```
`base.html`
```html
<!DOCTYPE html>
<html>
<head>
<title>Library</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
```
5. 在 `library` 项目中创建 URL:
```python
from django.urls import path
from books.views import book_list, book_detail
urlpatterns = [
path('', book_list, name='book_list'),
path('book/<int:pk>/', book_detail, name='book_detail')
]
```
6. 在 `library` 项目中设置上传文件的静态文件路径:
```python
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```
7. 运行开发服务器并访问:
```
$ python manage.py runserver
```
访问 `http://127.0.0.1:8000/` 即可查看图书列表。可以通过上传图书封面图片来添加图书的详细信息。
阅读全文