现在就来添加书籍吧。为他设计一条url。
1 path('book_add/', views.book_add, name='book_add'), # 走bood_add视图函数别忘了更改index.html添加书籍的这条a标签。
<a href="{% url 'book_add' %}" class="btn btn-default" style="margin-top:10px;margin-bottom: 10px">添加书籍</a>
添加书籍,代表要提交数据,所以form表单是少不了的。
而且,添加书籍还要为他添加与其对应的出版社,作者。所以视图就要获取所有出版社,作者,渲染到book_add.html页面。
视图部分:
1 def book_add(request): 2 pub_lt = Publish.objects.all() # 数据库获取所有出版社 3 author_lt = Author.objects.all() # 数据库获取所有作者 4 return render(request, 'book_add.html', {"pub_list": pub_lt, "author_list": author_lt})
模版部分(book_add.html):
1 {% extends 'base.html' %} 2 3 {% block title %} 4 <title>添加书籍</title> 5 {% endblock %} 6 7 {% block body %} 8 <h3>添加书籍</h3> 9 {% include 'form.html' %} 10 {% endblock %}
也许你会感到奇怪,为什么添加页面这么少代码。没错、就是这么少。因为用到了继承base.html。我只要写个form表单就行。可这也没看到form表单,因为后面图书还有个编辑页面。其实也是form表单。所以
这里有用到了抽取模版。把form表单抽取出来,使用的话是{% include 'form.html' %}。代表把form.html拿到这来。
模版部分(form.html):
1 <form action="" method="post"> 2 {% csrf_token %} 3 <div class="form-group"> 4 <label for="title">书籍名称</label> 5 <input type="text" name="title" class="form-control" id="title" value="{{ book.title }}"> 6 </div> 7 <div class="form-group"> 8 <label for="price">价格</label> 9 <input type="text" name="price" id="price" class="form-control" value="{{ book.price }}"> 10 </div> 11 <div class="form-group"> 12 <label for="pub_date">出版日期</label> 13 <input type="date" name="pub_date" class="form-control" id="pub_date" value="{{ book.pub_date|date:"Y-m-d" }}"> 14 </div> 15 <div class="form-group"> 16 <label for="">出版社</label> 17 <select name="pubs" id="" class="form-control"> 18 {% for pub in pub_list %} 19 {% if pub.id == book.publish.id %} 20 <option value="{{ pub.id }}" selected>{{ pub.name }}</option> 21 {% else %} 22 <option value="{{ pub.id }}">{{ pub.name }}</option> 23 {% endif %} 24 {% endfor %} 25 </select> 26 </div> 27 <div class="form-group"> 28 <label for="">作者</label> 29 <select name="authors" id="" class="form-control" multiple> 30 {% for author in author_list %}32 {% if author in book.author.all %} 33 <option value="{{ author.id }}" selected>{{ author.name }}</option> 34 {% else %} 35 <option value="{{ author.id }}">{{ author.name }}</option> 36 {% endif %} 38 {% endfor %} 39 </select> 40 </div> 41 <input type="submit" value="提交" class="btn btn-warning"> 42 </form>注意:

