Django图书商城系统实战开发-实现商品管理
# 假设我们已经有了一个Django模型Book
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Book
def manage_books(request):
# 获取所有图书
books = Book.objects.all()
return render(request, 'books.html', {'books': books})
def add_book(request):
# 添加新图书的逻辑
if request.method == 'POST':
title = request.POST['title']
author = request.POST['author']
price = request.POST['price']
new_book = Book.objects.create(title=title, author=author, price=price)
# 重定向到图书列表页面
return HttpResponseRedirect('/books/')
return render(request, 'add_book.html')
def edit_book(request, book_id):
# 编辑图书的逻辑
if request.method == 'POST':
title = request.POST['title']
author = request.POST['author']
price = request.POST['price']
book = Book.objects.get(id=book_id)
book.title = title
book.author = author
book.price = price
book.save()
# 重定向到图书列表页面
return HttpResponseRedirect('/books/')
book = Book.objects.get(id=book_id)
return render(request, 'edit_book.html', {'book': book})
def delete_book(request, book_id):
# 删除图书的逻辑
book = Book.objects.get(id=book_id)
book.delete()
# 重定向到图书列表页面
return HttpResponseRedirect('/books/')
这个代码实例提供了创建、编辑和删除图书的基础视图函数。它使用了Django的ORM来与数据库交互,并通过POST请求处理表单数据。这些函数应该与相应的模板和URL配置一起工作,以构建一个完整的图书商城系统。
评论已关闭