from django.shortcuts import render, redirect,HttpResponse # Create your views here. from django.forms import widgets as wid from django.forms import ModelForm from .models import * class BookForm(ModelForm): class Meta: model = Book fields = "__all__" labels = {"title": "书籍名称", "price": "价格"} widgets = { "title": wid.TextInput(attrs={"class": "form-control"}), "price": wid.TextInput(attrs={"class": "form-control"}), "date": wid.TextInput(attrs={"class": "form-control", "type": "date"}), "publish": wid.Select(attrs={"class": "form-control"}), "authors": wid.SelectMultiple(attrs={"class": "form-control"}), } error_messages = { "title": {"required": "不能为空"} } def booklist(request): book_list = Book.objects.all() return render(request,"booklist.html",locals()) def add(request): if request.method == "POST": form = BookForm(request.POST) if form.is_valid(): form.save() return redirect("/booklist/") else: return render(request,"add.html",locals()) form = BookForm() return render(request,"add.html",locals()) def edit(request,edit_book_id): edit_book = Book.objects.filter(pk=edit_book_id).first() if request.method == "POST": form = BookForm(request.POST, instance=edit_book) if form.is_valid(): form.save() # edit_book.update(request.POST) return redirect("/booklist/") form = BookForm(instance=edit_book) return render(request,"edit.html",locals()) def delete(request,delete_book_id): if delete_book_id: Book.objects.filter(pk=delete_book_id).first().delete() return redirect("/booklist/") else: return HttpResponse("数据不存在,出错了")