1. 新建项目
2、新建静态文件夹,在settings 中配置静态文件,配置数据库
3、配置 路由
4、各功能
4.1返回主页面
4.2 查看
{% extends 'home.html' %} {% block content %} <a href="{% url 'add_book' %}" class="btn btn-success">添加</a> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th>id</th> <th>书名</th> <th>价格</th> <th>出版时间</th> <th>出版社</th> <th>作者</th> <th>操作</th> </tr> </thead> <tbody> {% for book_obj in book_info %} <tr> <td>{{ book_obj.pk }}</td> <td>{{ book_obj.title }}</td> <td>{{ book_obj.price }}</td> <td>{{ book_obj.publish_time|date:'Y-m-d' }}</td> <td>{{ book_obj.publish.name }}</td> <td>{% for author_obj in book_obj.authors.all %} {% if forloop.last %} {{ author_obj.name }} {% else %} {{ author_obj.name }}, {% endif %} {% endfor %} </td> <td><a href="{% url 'edit_book' book_obj.pk %}" class="btn btn-warning">编辑</a> <a href="{% url 'delete_book' book_obj.pk %}" class="btn btn-danger">删除</a></td> </tr> {% endfor %} </tbody> </table> {% endblock %}html
4.3 新增书籍
def add_book(request): if request.method == 'POST': title = request.POST.get('title') price = request.POST.get('price') publish_time = request.POST.get('publish_time') publish = request.POST.get('publish') authors = request.POST.getlist('authors') # 新增数据 book_obj = models.Book.objects.create(title=title, price=price, publish_id=publish, publish_time=publish_time) # 手动新增book和author之间的外键关系 book_obj.authors.add(*authors) return redirect('book_info') # 把作者列表和出版社列表传递给前端 publish_list = models.Publish.objects.all() author_list = models.Author.objects.all() return render(request, 'add_book.html', locals())add_book
4.4 修改书籍
{% extends 'home.html' %} {% block content %} <h1 class="text-center">编辑书籍</h1> <form action="" method="post"> <p>书名:<input type="text" class="form-control" name="title" value="{{ edit_obj.title }}"></p> <p>价格:<input type="text" class="form-control" name="price" value="{{ edit_obj.price }}"></p> <p>出版时间:<input type="date" class="form-control" name="publish_time" value="{{ edit_obj.publish_time|date:'Y-m-d' }}" > </p> <p>出版社: <select name="publish" id="" class="form-control"> {% for publish_obj in publish_list %} {% if edit_obj.publish == publish_obj %} <option value="{{ publish_obj.pk }}" class="form-control" selected>{{ publish_obj.name }}</option> {% else %} <option value="{{ publish_obj.pk }}" class="form-control">{{ publish_obj.name }}</option> {% endif %} {% endfor %} </select> </p> <p>作者: <select name="authors" id="" class="form-control" multiple> {% for author_obj in author_list %} {% if author_obj in edit_obj.authors.all %} <option value="{{ author_obj.pk }}" selected>{{ author_obj.name }}</option> {% else %} <option value="{{ author_obj.pk }}">{{ author_obj.name }}</option> {% endif %} {% endfor %} </select> </p> <p> <input type="submit" class="btn btn-success pull-right"> </p> </form> {% endblock %}edit_book