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() 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() class Book(models.Model): nid = models.AutoField(primary_key=True)
title = models.CharField( max_length=32)
publishDate=models.DateField()
price=models.DecimalField(max_digits=5,decimal_places=2) # 999.99 # 与Publish建立一对多的关系,外键字段建立在多的一方
publish=models.ForeignKey(to="Publish",to_field="nid",on_delete=models.CASCADE)
# 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表
authors=models.ManyToManyField(to='Author',)

urls.py

from django.contrib import admin
from django.urls import path,re_path from book import views urlpatterns = [
path('admin/', admin.site.urls),
re_path('books/add/$', views.add_book),
re_path('books/$', views.books),
re_path('books/(\d+)/change/$', views.change_book),
re_path('books/(\d+)/delete/$', views.delete_book),
]

在settings里边

views.py

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

from .models import Publish,Author,Book
def add_book(request): if request.method=="POST":
title=request.POST.get("title")
price=request.POST.get("price")
pub_date=request.POST.get("pub_date")
publish_id=request.POST.get("publish_id")
authors_id_list=request.POST.getlist("authors_id_list") # checkbox,select book_obj=Book.objects.create(title=title,price=price,publishDate=pub_date,publish_id=publish_id)
print(authors_id_list) # ['2', '3'] book_obj.authors.add(*authors_id_list) return HttpResponse("success") publish_list=Publish.objects.all()
author_list=Author.objects.all() return render(request,"addbook.html",{"author_list":author_list,"publish_list":publish_list}) def books(request):
book_list = Book.objects.all()
return render(request, "book.html",{"book_list":book_list}) def change_book(request,edit_book_id):
edit_book_obj = Book.objects.filter(pk = edit_book_id).first()
if request.method == 'POST':
title = request.POST.get('title')
price = request.POST.get('price')
pub_date = request.POST.get('pub_date')
publish_id = request.POST.get('publish_id')
authors_id_list = request.POST.getlist('authors_id_list') Book.objects.filter(pk=edit_book_id).update(title=title, price=price,publishDate=pub_date, publish_id=publish_id)
# edit_book_obj.authors.clear()
# edit_book_obj.authors.add(*authors_id_list)
edit_book_obj.authors.set(authors_id_list) return redirect("/books/") publish_list = Publish.objects.all()
author_list = Author.objects.all() return render(request, 'editbook.html',{"edit_book_obj":edit_book_obj, "publish_list":publish_list, "author_list":author_list}) def delete_book(request, delete_book_id):
Book.objects.filter(pk=delete_book_id).delete()
return redirect("/books/")

addbook.html(添加书籍)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bs/css/bootstrap.css">
</head>
<body> <h3>添加书籍</h3> <div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="" method="post">
{% csrf_token %}
<div class="form-group">
<label for="">名称</label>
<input type="text" name="title" class="form-control" value="">
</div> <div class="form-group">
<label for="">价格</label>
<input type="text" name="price" class="form-control">
</div> <div class="form-group">
<label for="">出版日期</label>
<input type="date" name="pub_date" class="form-control">
</div> <div class="form-group">
<label for="">出版社</label>
<select name="publish_id" id="" class="form-control">
{% for publish in publish_list %}
<option value="{{ publish.pk }}">{{ publish.name }}</option>
{% endfor %}
</select>
</div> <div class="form-group">
<label for="">作者</label>
<select type="text" name="authors_id_list" multiple class="form-control">
{% for author in author_list %}
<option value="{{ author.pk }}">{{ author.name }}</option>
{% endfor %} </select>
</div>
<input type="submit" class="btn btn-default"> </form>
</div>
</div>
</div> </body>
</html>

book.html(查看书籍)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bs/css/bootstrap.css">
</head>
<body> <h3>查看书籍</h3> <div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2"> {# 边框、悬浮时变色、条纹编码 #}
<a href="/books/add" class="btn btn-primary">添加书籍</a>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>编号</th>
<th>书籍名称</th>
<th>价格</th>
<th>出版日期
<th>出版社</th>
<th>作者</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for book in book_list %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ book.title }}</td>
<td>{{ book.price }}</td>
<td>{{ book.publishDate|date:'Y-m-d' }}</td>
<td>{{ book.publish.name }}</td>
<td>
{% for author in book.authors.all %}
{% if forloop.last %}
<span>{{ author.name }}</span>
{% else %}
<span>{{ author.name }}</span>,
{% endif %}
{% endfor %} </td>
<td>
<a href="/books/{{ book.pk }}/change/" class="btn btn-warning">编辑</a>
<a href="/books/{{ book.pk }}/delete/" class="btn btn-danger">删除</a> </td>
</tr>
{% endfor %} </tbody>
</table>
</div>
</div>
</div> </body>
</html>

editbook.html(编辑书籍)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bs/css/bootstrap.css">
</head>
<body> <h3>编辑书籍</h3> <div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="" method="post">
{% csrf_token %}
<div class="form-group">
<label for="">名称</label>
<input type="text" name="title" class="form-control" value="{{ edit_book_obj.title }}">
</div> <div class="form-group">
<label for="">价格</label>
<input type="text" name="price" class="form-control" value="{{ edit_book_obj.price }}">
</div> <div class="form-group">
<label for="">出版日期</label>
<input type="date" name="pub_date" class="form-control"
value="{{ edit_book_obj.publishDate|date:'Y-m-d' }}">
</div> <div class="form-group">
<label for="">出版社</label>
<select name="publish_id" id="" class="form-control">
{% for publish in publish_list %}
<option selected value="{{ publish.pk }}">{{ publish.name }}</option>
{% if edit_book_obj.publish == publish %}
{% else %}
<option value="{{ publish.pk }}">{{ publish.name }}</option>
{% endif %} {% endfor %}
</select>
</div> <div class="form-group">
<label for="">作者</label>
<select type="text" name="authors_id_list" multiple class="form-control">
{% for author in author_list %}
{% if author in edit_book_obj.authors.all %}
<option selected value="{{ author.pk }}">{{ author.name }}</option>
{% else %}
<option value="{{ author.pk }}">{{ author.name }}</option>
{% endif %}
{% endfor %} </select>
</div>
<input type="submit" class="btn btn-default"> </form>
</div>
</div>
</div> </body>
</html>

练习|Django-多表的更多相关文章

  1. python运维开发(十九)----Django后台表单验证、session、cookie、model操作

    内容目录: Django后台表单验证 CSRF加密传输 session.cookie model数据库操作 Django后台Form表单验证 Django中Form一般有2种功能: 1.用于做用户提交 ...

  2. django form表单验证

    一. django form表单验证引入 有时时候我们需要使用get,post,put等方式在前台HTML页面提交一些数据到后台处理例 ; <!DOCTYPE html> <html ...

  3. django from表单验证

    django from表单验证   实现:表单验证 工程示例: urls.py 1 2 3 4 5 6 7 8 9 from django.conf.urls import url from djan ...

  4. Django 数据表更改

    Django 数据表更改 « Django 开发内容管理系统(第四天) Django 后台 » 我们设计数据库的时候,早期设计完后,后期会发现不完善,要对数据表进行更改,这时候就要用到本节的知识. D ...

  5. python 全栈开发,Day73(django多表添加,基于对象的跨表查询)

    昨日内容回顾 多表方案: 如何确定表关系呢? 表关系是在2张表之间建立的,没有超过2个表的情况. 那么相互之间有2条关系线,先来判断一对多的关系. 如果其中一张表的记录能够对应另外一张表的多条记录,那 ...

  6. python 全栈开发,Day72(昨日作业讲解,昨日内容回顾,Django多表创建)

    昨日作业讲解 1.图书管理系统 实现功能:book单表的增删改查 1.1 新建一个项目bms,创建应用book.过程略... 1.2 手动创建static目录,并在目录里面创建css文件夹,修改set ...

  7. Django:表结构发生变化需要执行命令

    Django:表结构发生变化需要执行命令 Django:表结构发生变化需要执行命令 mysite> python manage.py makemigrations blog #让 Django ...

  8. django Form表单的使用

    Form django表单系统中,所有的表单类都作为django.forms.Form的子类创建,包括ModelForm 关于django的表单系统,主要分两种 基于django.forms.Form ...

  9. Django(5) session登录注销、csrf及中间件自定义、django Form表单验证(非常好用)

    一.Django中默认支持Session,其内部提供了5种类型的Session供开发者使用: 数据库(默认) 缓存 文件 缓存+数据库 加密cookie 1.数据库Session 1 2 3 4 5 ...

  10. django删除表重建&修改用户密码&base64加密解密字符串&ps aux参数说明&各种Error例子

    1.django的queryset不支持负索引 AssertionError: Negative indexing is not supported. 2.django向前端JavaScript传递列 ...

随机推荐

  1. <转载>iTerm2使用技巧

    原文链接:http://www.cnblogs.com/756623607-zhang/p/7071281.html   1.设置窗口 定位到 [Preferences - Profiles - Wi ...

  2. golang使用simplejson库解析复杂json

    cnblogs原创 golang自带的json解析库encoding/json提供了json字符串到json对象的相互转换,在json字符串比较简单的情况下还是挺好用的,但是当json字符串比较复杂或 ...

  3. Python提示AttributeError 或者DeprecationWarning: This module was deprecated解决方法

    Python提示AttributeError 或者DeprecationWarning: This module was deprecated解决方法 在使用Python的sklearn库时,发现sk ...

  4. swift学习第一天---常量变量基础数据类型

    import Foundation /** * 1.常量 变量 知识要点:常量的定义用let 变量的定义用var 常量一旦定义便不可再更改. 变量定义之后可以在定义之后的程序中任意地方进行修改. */ ...

  5. mysql逗逼的.frm文件恢复数据库

    mysql数据库用.frm文件进行恢复. 背景:mac系统  .frm文件 (1)打开终端:输入cd /usr/local  回车. (2)输入 ls 回车. 这时候 打开finder ---> ...

  6. POI导出带格式的Excel模板——(六)

    Jar包

  7. ssh Jetson tk1

    背景: 因为TK1要放到智能车上,不方便打开roscore和各个节点,因此需要PC远程控制. 方法: 在PC端用ssh命令登录: (1)命令sudo ssh tegra-ubuntu.local(te ...

  8. Bootstrap2.x与Bootstrap3.x的区别

    做项目时,有时也会参考别的案例的优秀之处.在用Bootstrap的时候,发现很多项目代码都有区别,在<div>布局class上,有用.span*,有用.col-md-*,实际上是Boots ...

  9. WPF开发中的多线程的问题

    今天帮助同事做了一个WPF版的多线程demo,分享给大家. 要实现的问题就是非主线程thread1 去后台不停的取新数据,当有新数据的时候就会展示到前台. 我给他做的demo实现一个按秒的计数器,随着 ...

  10. 在全志平台调试博通的wifi驱动(类似ap6212)【转】

    转自:http://blog.csdn.net/fenzhi1988/article/details/44809779 调试驱动之前,首先先看看驱动代码,了解代码大致工作流程,再根据硬件配置驱动,比如 ...