创建model 对象
models.py
作者 作者详情 出版社 图书
from django.db import models # Create your models here. class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() authorDetail = models.OneToOneField("AuthorDetail") def __str__(self): return self.name class AuthorDetail(models.Model): nid = models.AutoField(primary_key=True) birthday = models.DateField() telephone = models.CharField(max_length=11) addr = models.CharField(max_length=64) class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(max_length=32) publishDate = models.DateField() publish = models.ForeignKey("Publish") authors = models.ManyToManyField("Author") def __str__(self): return self.title
数据库创建一些数据 create_bluk
import os if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tushu.settings") import django django.setup() from app01 import models import random l1 = [] for i in range(1, 101): obj = models.Book( title='哈哈%s' % i, # price=1+i, publishDate='2018-01-0%s' % (random.randint(1, 9)), publish_id=random.randint(1, 3), ) l1.append(obj) models.Book.objects.bulk_create(l1)
from.py 样式
from django import forms from app01 import models class MyForm(forms.Form): title = forms.CharField( max_length=32, min_length=2, error_messages={ "required": "内容不能为空", "min_length": "长度不能小于2位", "max_length": "长度不能大于32位", }, label="书名", ) publishDate = forms.DateField( label="出版日期", widget=forms.widgets.DateInput(attrs={"type": "date"}) ) publish = forms.ModelChoiceField( label="出版社", queryset=models.Publish.objects.all(), widget=forms.widgets.Select() ) authors = forms.ModelMultipleChoiceField( label="作者", queryset=models.Author.objects.all(), widget=forms.widgets.SelectMultiple() ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs.update({ "class": "form-control", # "error_messages": { # "required": "内容不能为空", # }, } )
视图 view
from django.shortcuts import render, HttpResponse, redirect # Create your views here. from app01 import models from form.form import MyForm from django.http import JsonResponse def show(request): all_books = models.Book.objects.all() return render(request, "show.html", {"all_books": all_books}) def create_book(request): if request.method == "GET": form_obj = MyForm() return render(request, "create_book.html", {"form_obj": form_obj}) else: data = request.POST form_obj = MyForm(data) if form_obj.is_valid(): data = form_obj.cleaned_data author_data = data.pop('authors') book_obj = models.Book.objects.create(**data) book_obj.authors.add(*author_data) return redirect("show") else: return render(request, "create_book.html", {"form_obj": form_obj}) def editor_book(request, n): book_obj = models.Book.objects.filter(pk=n) if request.method == "GET": book_obj = book_obj.first() all_publish = models.Publish.objects.all() all_authors = models.Author.objects.all() return render(request, 'editor_book.html', {"n": n, "book_obj": book_obj, "all_publish": all_publish, "all_authors": all_authors}) else: data = request.POST.dict() author_data = request.POST.getlist("authors") print(data, "++++++++++++++") print(author_data) # print(author_data['authors'],'----------------') del data["csrfmiddlewaretoken"] data.pop("authors") book_obj.update(**data) book_obj[0].authors.set(author_data) return redirect("show") def delete_book(request, n): models.Book.objects.filter(pk=n).delete() return redirect("show") def ajax_delete_book(request, n): data = {"status": False} if request.method == "POST": models.Book.objects.filter(pk=n).delete() data["status"] = True return JsonResponse(data) else: return JsonResponse(data) # try: # data['status'] = 1 # models.Book.objects.filter(pk=n).delete() # except Exception: # data['status'] = 2 # return JsonResponse(data)
html 页面
show.html
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>show</title> <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}"> </head> <body> <h1>书籍展示</h1> <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <a class="btn btn-primary" href="{% url 'create_book' %}">添加书籍</a> <table class="table table-bordered table-striped table-hover"> <thead> <tr> <th>序号</th> <th>书名</th> <th>出版日期</th> <th>出版社</th> <th>作者</th> <th>操作</th> </tr> </thead> <tbody> {% for book in all_books %} <tr> <td>{{ forloop.counter }}</td> <td>{{ book.title }}</td> <td>{{ book.publishDate|date:"Y-m-d" }}</td> <td>{{ book.publish.name }}</td> <td> {% for author in book.authors.all %} {{ author.name }} {% if forloop.last %} {% else %} , {% endif %} {% endfor %} </td> <td> <a href="{% url 'editor_book' book.pk %}" class="btn btn-warning">编辑</a> <a href="{% url 'delete_book' book.pk %} " class="btn btn-danger">删除</a> <button class="btn btn-danger ajaxbtn">ajax删除</button> <span class="hidden">{{ book.pk }}</span> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> <script src="{% static 'js/jquery-3.4.1.js' %}"></script> <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script> <script> $("tbody").on("click", ".ajaxbtn", function () { ths = $(this); var deleteId = ths.next().text(); $.ajax({ url: "/ajax_delete_book/" + deleteId + "/", type: "post", data: {"csrfmiddlewaretoken": "{{ csrf_token }}"}, success: function (data) { ths.parent().parent().remove(); var tr_list = $('tbody').children(); $.each(tr_list, function (k, v) { $(v).children().eq(0).text(k + 1); }) } }) }) </script> </body> </html>
create_book.html
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>show</title> <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}"> </head> <body> <h1>添加书籍</h1> <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> {#form表单#} <form action="{% url 'create_book' %}" method="post" novalidate> {% csrf_token %} {% for field in form_obj %} <div class="form-group {% if field.errors.0 %} has-error {% endif %} "> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field }} <span class="text-danger">{{ field.errors.0 }}</span> </div> {% endfor %} <input type="submit" class="btn btn-success pull-right" value="保存"> </form> </div> </div> </div> <script src="{% static 'js/jquery-3.4.1.js' %}"></script> <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script> </body> </html>
editor_book.html
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>show</title> <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}"> </head> <body> <h1>添加书籍</h1> <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> {#form表单#} <form action="{% url 'create_book' %}" method="post" novalidate> {% csrf_token %} {% for field in form_obj %} <div class="form-group {% if field.errors.0 %} has-error {% endif %} "> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field }} <span class="text-danger">{{ field.errors.0 }}</span> </div> {% endfor %} <input type="submit" class="btn btn-success pull-right" value="保存"> </form> </div> </div> </div> <script src="{% static 'js/jquery-3.4.1.js' %}"></script> <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script> </body> </html>