基于django的复杂图书二手交易系统代码实现
时间: 2023-07-26 10:11:28 浏览: 122
以下是一个基于Django的复杂图书二手交易系统的代码实现示例,包含了更多的功能和细节,仅供参考:
1. 数据库模型
```python
from django.db import models
from django.contrib.auth.models import User
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
publisher = models.CharField(max_length=200)
description = models.TextField()
price = models.DecimalField(max_digits=6, decimal_places=2)
image = models.ImageField(upload_to='book_covers/')
owner = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class Category(models.Model):
name = models.CharField(max_length=200)
class BookCategory(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
class Order(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
buyer = models.ForeignKey(User, on_delete=models.CASCADE)
quantity = models.IntegerField()
total_price = models.DecimalField(max_digits=6, decimal_places=2)
address = models.CharField(max_length=200)
payment_method = models.CharField(max_length=200)
status = models.CharField(max_length=200, default='Pending')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
```
2. 表单
```python
from django import forms
from .models import Book, Order
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ('title', 'author', 'publisher', 'description', 'price', 'image')
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ('quantity', 'address', 'payment_method')
```
3. 视图函数
```python
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from .models import Book, Order, Category, BookCategory
from .forms import BookForm, OrderForm
@login_required
def sell_book(request):
if request.method == 'POST':
form = BookForm(request.POST, request.FILES)
if form.is_valid():
book = form.save(commit=False)
book.owner = request.user
book.save()
categories = request.POST.getlist('categories')
for category_id in categories:
category = Category.objects.get(pk=category_id)
BookCategory.objects.create(book=book, category=category)
return redirect('book_detail', book_id=book.id)
else:
form = BookForm()
categories = Category.objects.all()
return render(request, 'sell_book.html', {'form': form, 'categories': categories})
def book_list(request):
query = request.GET.get('q')
if query:
books = Book.objects.filter(Q(title__icontains=query) | Q(author__icontains=query))
else:
books = Book.objects.all()
categories = Category.objects.all()
return render(request, 'book_list.html', {'books': books, 'categories': categories})
def book_detail(request, book_id):
book = get_object_or_404(Book, pk=book_id)
categories = book.bookcategory_set.all().values_list('category', flat=True)
related_books = Book.objects.filter(bookcategory__category__in=categories).exclude(pk=book_id)[:3]
return render(request, 'book_detail.html', {'book': book, 'related_books': related_books})
@login_required
def add_to_cart(request, book_id):
book = get_object_or_404(Book, pk=book_id)
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
order.book = book
order.buyer = request.user
order.total_price = order.quantity * book.price
order.save()
return redirect('cart')
else:
form = OrderForm()
return render(request, 'add_to_cart.html', {'book': book, 'form': form})
@login_required
def cart(request):
orders = Order.objects.filter(buyer=request.user)
return render(request, 'cart.html', {'orders': orders})
@login_required
def checkout(request):
orders = Order.objects.filter(buyer=request.user, status='Pending')
total_price = sum(order.total_price for order in orders)
if request.method == 'POST':
for order in orders:
order.address = request.POST.get('address')
order.payment_method = request.POST.get('payment_method')
order.status = 'Paid'
order.save()
return redirect('order_history')
return render(request, 'checkout.html', {'orders': orders, 'total_price': total_price})
@login_required
def order_history(request):
orders = Order.objects.filter(buyer=request.user).order_by('-created_at')
return render(request, 'order_history.html', {'orders': orders})
@login_required
def sell_history(request):
books = Book.objects.filter(owner=request.user)
orders = Order.objects.filter(book__in=books).order_by('-created_at')
return render(request, 'sell_history.html', {'orders': orders})
```
4. URL配置
```python
from django.urls import path
from . import views
urlpatterns = [
path('sell_book/', views.sell_book, name='sell_book'),
path('book_list/', views.book_list, name='book_list'),
path('book_detail/<int:book_id>/', views.book_detail, name='book_detail'),
path('add_to_cart/<int:book_id>/', views.add_to_cart, name='add_to_cart'),
path('cart/', views.cart, name='cart'),
path('checkout/', views.checkout, name='checkout'),
path('order_history/', views.order_history, name='order_history'),
path('sell_history/', views.sell_history, name='sell_history'),
]
```
5. 模板
sell_book.html
```html
{% extends 'base.html' %}
{% block content %}
<h2>Sell a Book</h2>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<p>Categories:</p>
{% for category in categories %}
<label>
<input type="checkbox" name="categories" value="{{ category.id }}"> {{ category.name }}
</label>
{% endfor %}
<button type="submit">Submit</button>
</form>
{% endblock %}
```
book_list.html
```html
{% extends 'base.html' %}
{% block content %}
<h2>Book List</h2>
<form method="get">
<input type="text" name="q" placeholder="Search...">
<button type="submit">Search</button>
</form>
<p>Categories:</p>
<ul>
<li><a href="{% url 'book_list' %}">All</a></li>
{% for category in categories %}
<li>
<a href="{% url 'book_list' %}?category={{ category.id }}">{{ category.name }}</a>
</li>
{% endfor %}
</ul>
<ul>
{% for book in books %}
<li>
<a href="{% url 'book_detail' book.id %}">
{{ book.title }} by {{ book.author }}
</a>
- {{ book.price }}
<a href="{% url 'add_to_cart' book.id %}">Add to Cart</a>
</li>
{% endfor %}
</ul>
{% endblock %}
```
book_detail.html
```html
{% extends 'base.html' %}
{% block content %}
<h2>{{ book.title }} by {{ book.author }}</h2>
<img src="{{ book.image.url }}" alt="{{ book.title }}">
<p>{{ book.description }}</p>
<p>Price: {{ book.price }}</p>
<p>Categories:</p>
<ul>
{% for category in book.bookcategory_set.all %}
<li>{{ category.category.name }}</li>
{% endfor %}
</ul>
<a href="{% url 'add_to_cart' book.id %}">Add to Cart</a>
<h3>Related Books</h3>
<ul>
{% for related_book in related_books %}
<li>
<a href="{% url 'book_detail' related_book.id %}">
{{ related_book.title }} by {{ related_book.author }}
</a>
</li>
{% endfor %}
</ul>
{% endblock %}
```
add_to_cart.html
```html
{% extends 'base.html' %}
{% block content %}
<h2>Add to Cart - {{ book.title }}</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
```
cart.html
```html
{% extends 'base.html' %}
{% block content %}
<h2>Cart</h2>
<ul>
{% for order in orders %}
<li>
{{ order.book.title }} x {{ order.quantity }} - {{ order.total_price }}
</li>
{% endfor %}
</ul>
<a href="{% url 'checkout' %}">Checkout</a>
{% endblock %}
```
checkout.html
```html
{% extends 'base.html' %}
{% block content %}
<h2>Checkout</h2>
<ul>
{% for order in orders %}
<li>
{{ order.book.title }} x {{ order.quantity }} - {{ order.total_price }}
</li>
{% endfor %}
</ul>
<p>Total Price: {{ total_price }}</p>
<form method="post">
{% csrf_token %}
<label>
Address:
<textarea name="address" required></textarea>
</label>
<label>
Payment Method:
<select name="payment_method" required>
阅读全文