django前端渲染多对多关系(比如一本书的作者有哪些)
自己遇到的问题是,前端渲染不出多对多关系,咨询Yuan后解决,特此记录。
urls.py
from django.conf.urls import url
from book import views urlpatterns = [
url(r'^index/', views.index),
url(r'^add/', views.add),
url(r'^delete/', views.delete),
url(r'^modify/', views.modify),
]
models.py
from django.db import models # Create your models here. class Publisher(models.Model):
name = models.CharField(max_length=, verbose_name="名称")
address = models.CharField("地址", max_length=)
city = models.CharField('城市', max_length=)
state_province = models.CharField(max_length=)
country = models.CharField(max_length=)
website = models.URLField() class Meta:
verbose_name = '出版商'
verbose_name_plural = verbose_name def __str__(self):
return self.name class Author(models.Model):
name = models.CharField(max_length=) def __str__(self):
return self.name class AuthorDetail(models.Model):
# sex = models.BooleanField(max_length=, choices=((, '男'), (, '女'),))
sex = models.CharField(max_length=)
email = models.EmailField()
address = models.CharField(max_length=)
birthday = models.DateField()
author = models.OneToOneField(Author) def __str__(self):
return '(%s,%s,%s)' % (self.sex, self.email, self.address) class Book(models.Model):
title = models.CharField(max_length=)
price = models.DecimalField(max_digits=, decimal_places=, default=)
authors = models.ManyToManyField('Author')
publisher = models.ForeignKey('Publisher')
publication_date = models.DateField(default='2017-08-20') def __str__(self):
return self.title
views.py
def index(request):
all_book_list = Book.objects.all() # 获取所有book对象
if request.method == "POST": # 搜索框的POST请求和数据
key_word = request.POST.get('key_word')
all_book_list = Book.objects.filter(title__contains=key_word)
return render(request, "book/index.html", {"all_book_list": all_book_list})
book/book.index.html
<!--{% load book_to_author %}-->
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>内部管理系统</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style>
        ul{
            padding: 20px 30px 20px 50px;
        }
        ul li {
            margin: 30px ;
        }
        {#   分割    #}
        .outer{
            margin: 100px auto;
            width: %;
            height: 400px;
            border: 1px solid rebeccapurple;
            position: relative;
        }
        .search_form {
            position: absolute;
            top: 10px;
            left: 750px;
        }
        .table-content {
            position: absolute;
            top: 50px;
        }
        .form {
            display: inline-block;
        }
        .add-button{
            position: absolute;
            right: 20px;
            bottom: 20px;
        }
    </style>
    <link rel="stylesheet" href="{% static "dist/css/bootstrap.css" %}">
</head>
<body>
<ul id="myTab" class="nav nav-tabs">
    <li class="active">
       <a href="#book" data-toggle="tab">书籍管理</a>
    </li>
    <li>
        <a href="/author/index">作者管理</a>
    </li>
    <li>
        <a href="/publisher/index">出版社管理</a>
    </li>
    <li class="dropdown">
       <a href="#" id="myTabDrop1" class="dropdown-toggle"
          data-toggle="dropdown">学科<b class="caret"></b>
       </a>
        <ul class="dropdown-menu" role="menu" aria-labelledby="myTabDrop1">
            <li><a href="#yuwen" tabindex="-1" data-toggle="tab">
                语文</a>
            </li>
            <li><a href="#shuxue" tabindex="-1" data-toggle="tab">
                数学</a>
            </li>
        </ul>
    </li>
</ul>
<div id="myTabContent" class="tab-content">
    <div class="tab-pane fade in active" id="book">
        <div class="outer">
            <form class="col-lg-2 input-group search_form" action="/index/" method="post">
                <input class="form-control form" placeholder="Search for..." type="text" name="key_word">
                <!--<input type="submit" value="">-->
                 <span class="input-group-btn">
                    <input class="btn btn-default" type="submit">Go2!</input>
                 </span>
            </form>
            <table class="table table-striped table-content">
            <tbody>
                <tr>
                    <th>编号</th>
                    <th>书名</th>
                    <th>价格</th>
                    <th>作者</th>
                    <th>出版社</th>
                    <th>出版日期</th>
                    <th>         action</th>
                </tr>
              {% for book in all_book_list %}
                   <tr>
                        <td>{{ book.id  }}</td>
                        <td>{{ book.title }}</td>
                        <td>{{ book.price }}</td>
                        <td>{{ book.authors }}</td>  //这块是问题点
                        <td>{{ book.publisher }}</td>
                        <td>{{ book.publication_date|date:'Y-m-d'}}</td>
                       <td>
                           <a href="/book/delete/?id={{ book.id }}"><button  type="button" class="btn btn-danger">删除</button></a>
                           <!-- Button trigger modal -->
                           <button type="button" class="btn btn-primary modify" data-toggle="modal" data-target="#myModal">编辑</button>
                       </td>
                   </tr>
                {% endfor %}
            </tbody>
            </table>
            <a href="/book/add/"><button type="button" class="btn btn-primary add-button">添加</button></a>
        </div>
        <!-- Modal -->
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                  <h4 class="modal-title" id="myModalLabel">编辑模式</h4>
              </div>
            <form action="/book/modify/" method="post">
                <div class="modal-body">
                    <div class="input-group">
                    <span class="input-group-addon" id="basic-addon1">ID</span>
                    <input type="text" class="form-control BookId" aria-describedby="basic-addon1" name="BookId">
                    </div>
                    <div class="input-group">
                    <span class="input-group-addon" id="basic-addon1">书名</span>
                    <input type="text" class="form-control BookName" aria-describedby="basic-addon1" name="BookName">
                    </div>
                    <div class="input-group">
                    <span class="input-group-addon" id="basic-addon1">价格</span>
                    <input type="text" class="form-control Price" aria-describedby="basic-addon1" name="Price">
                    </div>
                    <div class="input-group">
                    <span class="input-group-addon" id="basic-addon1">作者</span>
                    <input type="text" class="form-control Author" aria-describedby="basic-addon1" name="Author">
                    </div>
                    <div class="input-group">
                    <span class="input-group-addon" id="basic-addon1">出版社</span>
                    <input type="text" class="form-control Publisher" aria-describedby="basic-addon1" name="Publisher">
                    </div>
                    <div class="input-group">
                    <span class="input-group-addon" id="basic-addon1">出版日期</span>
                    <input type="text" class="form-control Publication_date" aria-describedby="basic-addon1" name="Publication_date">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary" id="modify_confirm">Save changes</button>
                </div>
            </form>
            </div>
          </div>
        </div>
    </div>
    <div class="tab-pane fade" id="author">
    </div>
    <div class="tab-pane fade" id="publisher">
    </div>
    <div class="tab-pane fade" id="jmeter">
        <p>语文。。。。</p>
    </div>
    <div class="tab-pane fade" id="ejb">
        <p>数学。。。。。</p>
    </div>
</div>
    <!--page bottom js-->
    <script src="{% static "dist/js/BookManagerSystem_book.js" %}"></script>
</body>
</html>
在前端模板语言中,如上方式使用
<td>{{ book.authors }}</td>  
结果:

使用
<td>{{ book.authors.all }}</td>  
结果

使用:
{% for book_author in {{ book.authors.all }} %}
         <td>{{ book_author }}</td>
{% endfor %}  
效果

使用:
{% for book_author in book.authors.all %}
          <td>{{ book_author }}</td>
 {% endfor %}  
效果

正确的做法:
            {% for book in all_book_list %}
                   <tr>
                        <td>{{ book.id  }}</td>
                        <td>{{ book.title }}</td>
                        <td>{{ book.price }}</td>
                       <td>
                            {% for book_author in book.authors.all %}
                                {{ book_author }}
                            {% endfor %}
                       </td>  //将循环放在td标签内
                        <td>{{ book.publisher }}</td>
                        <td>{{ book.publication_date|date:'Y-m-d'}}</td>
                       <td>
                           <a href="/book/delete/?id={{ book.id }}"><button  type="button" class="btn btn-danger">删除</button></a>
                           <!-- Button trigger modal -->
                           <button type="button" class="btn btn-primary modify" data-toggle="modal" data-target="#myModal">编辑</button>
                       </td>
                   </tr>
                {% endfor %}
效果

哎~~~踩坑的地方,以为在{% for %} 内部循环的时候变量也要使用{{变量名}},其实不用,另外td和元素的嵌套关系没设置正确~~~
django前端渲染多对多关系(比如一本书的作者有哪些)的更多相关文章
- Django学习--9          多对一关系模型
		保持前面的不变只是增加了一些 1.vim sdj/models.py class Blog(models.Model): name = models.CharField(max_leng ... 
- django -- 多对多关系的实现
		在django中表和表之间的多对多关系有两种实现方案: 方案一:直接使用django自动实现的多对多关系. 方案二:自己写连接表.然而告诉django在实现多对多关系时要使用的连接表. 一.方案一: ... 
- django笔记-模型数据模板呈现过程记录(多对多关系)
		首先,推荐一个网址:http://www.tuicool.com/articles/BfqYz2F,因为这里的比我的要有条理,更有利于各位的理解. 以下仅为为个人一次不完整的笔记: 环境:ubuntu ... 
- Django多对多关系建立及Form组件
		目录 Django多对多关系 1.创建方式一全自动 2.创建方式二纯手撸 3.半自动(推荐使用) forms校验组件 使用forms组件实现注册功能 form常用字段和插件 数据校验 钩子函数 HOO ... 
- Django中多对多关系的orm表设计
		作者的管理 1.设计表结构 出版社 书籍 作者 一个出版社出版多个书籍 1对多 书籍和作者的关系:一个作者写多本书,一本书可以是多个作者写.多对多 1)创建一张表,表中多对多的数据关系.使用 多对多 ... 
- Django 一对多,多对多关系解析
		[转]Django 一对多,多对多关系解析 Django 的 ORM 有多种关系:一对一,多对一,多对多. 各自定义的方式为 : 一对一: OneToOneField ... 
- django ORM模型表的一对多、多对多关系、万能双下划线查询
		一.外键使用 在 MySQL 中,如果使用InnoDB引擎,则支持外键约束.(另一种常用的MyIsam引擎不支持外键) 定义外键的语法为fieldname=models.ForeignKey(to_c ... 
- Django 之多对多关系
		1. 多对多关系 作者 <--> 书籍 1. 表结构设计 1. SQL版 -- 创建作者表 create table author( id int primary key auto_inc ... 
- Linux下开发python django程序(django数据库多对多关系)
		1.多对多关系数据访问 models.py设置 from django.db import models # Create your models here. sex_choices=( ('f',' ... 
随机推荐
- opencv c++编译
			g++ image2png.cpp -o test `pkg-config --cflags --libs opencv` 
- React脚手架less的安装
			最近在用react.js 结合蚂蚁金服的 Ant Design Mobile 做一个单页面的应用程序,遇到了一个很棘手的问题——那就是 react脚手架不支持less,看了不少优秀博主如何在react ... 
- JavaScript -- 操作符和逻辑运算
			算数操作符 + : 加 - : 减 * : 乘 / : 除 %:取余 递增和递减 1.递增 ++a与a++都是对a进行递增的操作 区别 ++a先返回递增之后的a的值 a++先返回a的原值,再返回递增之 ... 
- 修改Windows默认调试器
			程序崩溃时,系统会弹窗让你选择是否进行调试,可以设置系统默认调试器. 注册表位置: HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows NT/CurrentVe ... 
- MySQL 数据备份与还原的示例代码
			MySQL 数据备份与还原的示例代码 这篇文章主要介绍了MySQL 数据备份与还原的相关知识,本文通过示例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下 一.数据备份 1.使用 ... 
- redis基础知识学习
			数据结构:1.String 添加: set key value get key getset key value (先get再set) incr key (key对应value原子性递增1) decr ... 
- ssh整合思想 Spring分模块开发 crud参数传递 解决HTTP Status 500 - Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or(增加事务)
			在Spring核心配置文件中没有增加事务方法,导致以上问题 Action类UserAction package com.swift.action; import com.opensymphony.xw ... 
- Pig Latin-freecodecamp算法题目
			Pig Latin 1.要求 Pig Latin把一个英文单词的第一个辅音或辅音丛(consonant cluster)移到词尾,然后加上后缀 "ay". 如果单词以元音开始,你只 ... 
- Python基础——数值
			运算 运算 运算符 示例 加 + 减 - 乘 * 除 / 取余 % 幂 ** 赋值 = 绝对值 abs 取整(四舍五入) round 最大值 max 最小值 min 科学计数法 e 十六进制 0x 逻 ... 
- 20181210(os,os.path,subprocess,configparser,shutil)
			1.os模块 os表示操作系统,该模块主要处理与操作系统相关的操作.最常用的是文件操作:打开,读取,删除,复制,重命名. 重点掌握增删改查的函数操作. import os# 获取当前执行文件所在文件夹 ... 
