django框架两个使用模板实例


Posted in Python onDecember 11, 2019

本文实例讲述了django框架使用模板。分享给大家供大家参考,具体如下:

models.py:

from django.db import models
# Create your models here.
class Book(models.Model):
  title=models.CharField(max_length=32,unique=True)
  price=models.DecimalField(max_digits=8,decimal_places=2,null=True)
  pub_date=models.DateField()
  publish=models.CharField(max_length=32)
  is_pub=models.BooleanField(default=True)
  authors=models.ManyToManyField(to="Author")
class AuthorDetail(models.Model):
  gf=models.CharField(max_length=32)
  tel=models.CharField(max_length=32)
class Author(models.Model):
  name=models.CharField(max_length=32)
  age=models.IntegerField()
  # 与AuthorDetail建立一对一的关系
  # ad=models.ForeignKey(to="AuthorDetail",to_field="id",on_delete=models.CASCADE,unique=True)
  #OneToOneField 表示创建一对一关系。on_delete=models.CASCADE 表示级联删除。假设a表删除了一条记录,b表也还会删除对应的记录
  ad=models.OneToOneField(to="AuthorDetail",to_field="id",on_delete=models.CASCADE,)

urls.py:

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
  url(r'^admin/', admin.site.urls),
  # url(r'',views.index),#这一条不能放上面,会造成死循环
  url(r'index/$',views.index),
  url(r'books/add/$',views.add),
  url(r'books/manage/',views.manage),
  url(r'books/delete/(?P<id>\d+)',views.delete),
  url(r'books/modify/(?P<id>\d+)',views.modify),
]

views.py:

from django.shortcuts import render,HttpResponse
from app01 import models
# Create your views here.
def index(request):
  ret=models.Book.objects.all().exists()#True 和 False
  if ret:
    book_list=models.Book.objects.all()
    return render(request,'index.html',{'book_list':book_list})
  else:
    # hint='<script>alert("没有书籍,请添加书籍");window.location.href="/books/add" rel="external nofollow" rel="external nofollow" </script>'
    hint='<script>alert("没有书籍,请添加书籍");window.location.href="/books/add/" rel="external nofollow" </script>'
    return HttpResponse(hint)
def add(request):
  if request.method=="POST":
    title=request.POST.get("title")
    price=request.POST.get("price")
    pub_date=request.POST.get("pub_date")
    publish=request.POST.get("publish")
    is_pub=request.POST.get("is_pub")
    #插入一条记录
    obj=models.Book.objects.create(title=title,price=price,publish=publish,pub_date=pub_date,is_pub=is_pub)
    print(obj.title)
    hint = '<script>alert("添加成功");window.location.href="/index/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" </script>'
    return HttpResponse(hint)
  return render(request,"add.html")
def manage(request):
  ret=models.Book.objects.all().exists()
  print(ret)
  if ret:
    book_list=models.Book.objects.all()
    return render(request,"manage.html",{"book_list":book_list})
  else:
    hint='<script>alert("没有书籍,请添加书籍");window.location.href="/books/add" rel="external nofollow" rel="external nofollow" </script>'
    return HttpResponse(hint)
def delete(request,id):
  ret=models.Book.objects.filter(id=id).delete()
  print('删除记录%s'%ret)
  if ret[0]:
    hint='<script>alert("删除成功");window.location.href="/index/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" </script>'
    return HttpResponse(hint)
  else:
    hint='<script>alert("删除失败");window.location.href="/index/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" </script>'
    return HttpResponse(hint)
def modify(request,id):
  if request.method=="POST":
    title=request.POST.get('title')
    price = request.POST.get("price")
    pub_date = request.POST.get("pub_date")
    publish = request.POST.get("publish")
    is_pub = request.POST.get("is_pub")
    # 更新一条记录
    ret = models.Book.objects.filter(id=id).update(title=title, price=price, publish=publish, pub_date=pub_date,
                            is_pub=is_pub)
    print('更新记录%s'%ret)
    if ret: # 判断返回值为1
      hint = '<script>alert("修改成功");window.location.href="/index/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" </script>'
      return HttpResponse(hint) # js跳转
    else: # 返回为0
      hint = '<script>alert("修改失败");window.location.href="/index/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" </script>'
      return HttpResponse(hint) # js跳转
  book=models.Book.objects.get(id=id)
  return render(request,"modify.html",{"book":book})

index.html:

{% extends 'base.html' %}
{% block title %}
  <title>查看书籍</title>
{% endblock title %}
{% block content %}
  <h3>查看书籍</h3>
  <table class="table table-hover table-striped ">
        <thead>
           <tr>
             <th>名称</th>
             <th>价格</th>
             <th>出版日期</th>
             <th>出版社</th>
             <th>是否出版</th>
           </tr>
        </thead>
        <tbody>
           {% for book in book_list %}
           <tr>
             <td>{{ book.title }}</td>
             <td>{{ book.price }}</td>
             <td>{{ book.pub_date|date:"Y-m-d" }}</td>
             <td>{{ book.publish }}</td>
             <td>
               {% if book.is_pub %}
               已出版
               {% else %}
               未出版
               {% endif %}
             </td>
           </tr>
           {% endfor %}
        </tbody>
      </table>
{% endblock content %}

add.html:

{% extends 'base.html' %}
{% block title %}
<title>添加书籍</title>
{% endblock title %}
{% block content %}
<h3>添加书籍</h3>
<form action="" method="post">
   {% csrf_token %}
   <div class="form-group">
    <label for="">书籍名称</label>
    <input type="text" name="title" class="form-control">
  </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>
     <input type="text" name="publish" class="form-control">
  </div>
  <div class="form-group">
     <label for="">是否出版</label>
    <select name="is_pub" id="" class="form-control">
      <option value="1">已出版</option>
      <option value="0" selected="selected">未出版</option>
    </select>
  </div>
  <input type="submit" class="btn btn-success pull-right" value="添加">
</form>
{% endblock content %}

base.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  {% block title %}
  <title>Title</title>
  {% endblock title %}
  <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" >
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .header {
      width: 100%;
      height: 60px;
      background-color: #369;
    }
    .title {
      line-height: 60px;
      color: white;
      font-weight: 100;
      margin-left: 20px;
      font-size: 20px;
    }
    .container{
      margin-top: 20px;
    }
  </style>
</head>
<body>
<div class="header">
  <p class="title">
    书籍操作
  </p>
</div>
<div class="container">
  <div class="row">
    <div class="col-md-3">
      <div class="panel panel-danger">
        <div class="panel-heading"><a href="http://127.0.0.1:8000/index/" rel="external nofollow" >查看书籍</a></div>
        <div class="panel-body">
          Panel content
        </div>
      </div>
      <div class="panel panel-success">
        <div class="panel-heading"><a href="http://127.0.0.1:8000/books/add/" rel="external nofollow" >添加书籍</a></div>
        <div class="panel-body">
          Panel content
        </div>
      </div>
      <div class="panel panel-warning">
        <div class="panel-heading"><a href="http://127.0.0.1:8000/books/manage/" rel="external nofollow" >管理书籍</a></div>
        <div class="panel-body">
          Panel content
        </div>
      </div>
    </div>
    <div class="col-md-9">
      {% block content %}
      {% endblock content %}
    </div>
  </div>
</div>
</body>
</html>

manage.py:

{% extends 'base.html' %}
{% block title %}
  <title>管理书籍</title>
{% endblock title %}
{% block content %}
  <h3>管理书籍</h3>
<table class="table table-hover table-striped ">
        <thead>
           <tr>
             <th>名称</th>
             <th>价格</th>
             <th>出版日期</th>
             <th>出版社</th>
             <th>是否出版</th>
             <th>删除</th>
             <th>编辑</th>
           </tr>
        </thead>
        <tbody>
           {% for book in book_list %}
           <tr>
             <td>{{ book.title }}</td>
             <td>{{ book.price }}</td>
             <td>{{ book.pub_date|date:"Y-m-d" }}</td>
             <td>{{ book.publish }}</td>
             <td>
               {% if book.is_pub %}
               已出版
               {% else %}
               未出版
               {% endif %}
             </td>
             <td>
               <a href="/books/delete/{{ book.id }}" rel="external nofollow" >
                 <button type="button" class="btn btn-danger" data-toggle="modal" id="modelBtn">删除</button>
               </a>
             </td>
             <td>
                <a href="/books/modify/{{ book.id }}" rel="external nofollow" >
                  <button type="button" class="btn btn-success" data-toggle="modal">编辑</button>
                </a>
             </td>
           </tr>
           {% endfor %}
        </tbody>
      </table>
{% endblock content %}

modify.py:

{% extends 'base.html' %}
{% block title %}
<title>修改书籍</title>
{% endblock title %}
{% block content %}
<h3>修改书籍</h3>
<form action="" method="post">
   {% csrf_token %}
   <div class="form-group">
    <label for="">书籍名称</label>
    <input type="text" name="title" class="form-control" value="{{ book.title }}">
  </div>
  <div class="form-group">
    <label for="">价格</label>
    <input type="text" name="price" class="form-control" value="{{ book.price }}">
  </div>
  <div class="form-group">
     <label for="">出版日期</label>
    <input type="date" name="pub_date" class="form-control" value="{{ book.pub_date|date:"Y-m-d" }}">
  </div>
  <div class="form-group">
     <label for="">出版社</label>
     <input type="text" name="publish" class="form-control" value="{{ book.publish }}">
  </div>
  <div class="form-group">
     <label for="">是否出版</label>
    <select name="is_pub" id="" class="form-control">
      {% if book.is_pub %}
        <option value="1" selected="selected">已出版</option>
        <option value="0">未出版</option>
      {% else %}
        <option value="1">已出版</option>
        <option value="0" selected="selected">未出版</option>
      {% endif %}
    </select>
  </div>
  <input type="submit" class="btn btn-default pull-right" value="修改">
</form>
{% endblock content %}

django框架两个使用模板实例

django使用一对多和多对多关系建表之后的增删改查

-------models.py-----

from django.db import models
# Create your models here.
class Book(models.Model):
  title=models.CharField(max_length=32)
  price=models.DecimalField(max_digits=6,decimal_places=2)
  create_time=models.DateField()
  memo=models.CharField(max_length=32,default="")
  publish=models.ForeignKey(to="Publish",default=1)
  author=models.ManyToManyField("Author")#on_delete=models.CASCADE()默认级联删除
  def __str__(self):
    return self.title
class Publish(models.Model):
  name=models.CharField(max_length=32)
  email=models.CharField(max_length=32)
class Author(models.Model):
  name=models.CharField(max_length=32)
  def __str__(self): return self.name

-----urls.py----

from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
  url(r'^admin/', admin.site.urls), 
  url(r'^books/$',views.books), #查看
  url(r'^addbook/$',views.addbook), #增加
  url(r'^delbook/(\d+)/$',views.delbook), #删除
  url(r'editbook/(\d+)/$',views.editbook), #修改
]

----views.py 在app01下面-------

from django.shortcuts import render,HttpResponse,redirect
from .models import * 
def books(request):
  book_list=Book.objects.all()
  return render(request,"books.html",locals())
def addbook(request):
  if request.method=="POST":
    title=request.POST.get("title") #get方法取的是html页面中的name属性
    price= request.POST.get("price")
    date = request.POST.get("date")
    publish_id=request.POST.get("publish_id")
    # author_id_list = request.POST.get("author_id_list") #此方法只能取到最后一个值
    author_id_list = request.POST.getlist("author_id_list") #有多个值的注意要用getlist
    #绑定书籍与出版社一对多的关系
    obj=Book.objects.create(title=title,price=price,create_time=date,publish_id=publish_id)
    #绑定书籍与作者多对多的关系
    obj.author.add(*author_id_list)
    # obj.author.remove(1,2) #解除关系
    # obj.author.clear() #清空所有关系
    return redirect("/books/")
  else:
    publish_list=Publish.objects.all()
    author_list=Author.objects.all()
  return render(request,"addbook.html",locals())
def delbook(request,id):
  Book.objects.filter(id=id).delete()
  return redirect("/books/")
def editbook(request,id):
  if request.method=="POST":
    title=request.POST.get("title") #get方法取的是html页面中的name属性
    price=request.POST.get("price") 
    date=request.POST.get("date")
    publish_id=request.POST.get("publish_id")
    author_id_list=request.POST.getlist("author_id_list")
    Book.objects.filter(id=id).update(title=title,price=price,create_time=date,publish_id=publish_id)
    book=Book.objects.filter(id=id).first()
    # book.author.clear()
    # book.author.add(*author_id_list)
    book.author.set(author_id_list) #相当于上面两条
    return redirect ("/books/")
  edit_obj=Book.objects.filter(id=id).first() #加first从queryset得到 models对象
  publish_list = Publish.objects.all()
  author_list = Author.objects.all()
  return render(request,"editbook.html",locals())

----books.html----

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="/static/bs/css/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
</head>
<body>
<div class="container" style="margin-top:100px">
  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <a href="/addbook/" rel="external nofollow" ><button class="btn btn-primary">添加数据</button></a>
      <table class="table table-bordered table-striped">
      <thead>
      <tr>
      <th>序号</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.create_time|date:"Y-m-d" }}</td>
        <td>{{ book.publish.name }}</td>
        <td> {% for author in book.author.all %}
          {{ author.name }}
          {% if not forloop.last %}
            ,
          {% endif %}
          {% endfor %}
        </td>
        <td>
          <a href="/delbook/{{ book.pk }}/" rel="external nofollow" >删除</a>
          <a href="/editbook/{{ book.pk }}/" rel="external nofollow" >编辑</a>
        </td>
        </tr>
      {% endfor %}
      </tbody>
      </table>
    </div>
  </div>
</div>
</body>
</html>

-----addbook.html-----

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="/static/bs/css/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
</head>
<body>
<div class="container" style="margin-top:100px">
  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <form action="/addbook/" method="post">
        {% csrf_token %}
        <p>书籍名称<input type="text" name="title"></p>
        <p>书籍价格<input type="text" name="price"></p>
        <p>出版日期<input type="text" name="date"></p>
        <p><select name="publish_id" id="">
          {% for publish in publish_list %}
          <option value="{{ publish.pk }}">{{ publish.name }}</option>
          {% endfor %}
        </select>
        </p>
        <p><select name="author_id_list" id="" multiple>
          {% for author in author_list %}
          <option value="{{ author.pk }}">{{ author.name }}</option>
          {% endfor %}
        </select>
        </p>
        <input type="submit" class="btn btn-default">
      </form>
    </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" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
</head>
<body>
<div class="container" style="margin-top:100px">
  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <form action="/editbook/{{ edit_obj.id }}/" method="post">
        {% csrf_token %}
        <p>书籍名称<input type="text" name="title" value="{{ edit_obj.title }}"></p>
        <p>书籍价格<input type="text" name="price" value="{{ edit_obj.price }}"></p>
        <p>出版日期<input type="text" name="date" value="{{ edit_obj.create_time|date:"Y-m-d" }}"></p>
        <p><select name="publish_id" id="">
          {% for publish in publish_list %}
            {% if edit_obj.publish == publish %}
            <option selected value="{{ publish.pk }}">{{ publish.name }}</option>
            {% else %}
            <option value="{{ publish.pk }}">{{ publish.name }}</option>
            {% endif %}
          {% endfor %}
        </select>
        </p>
        <p><select name="author_id_list" id="" multiple>
          {% for author in author_list %}
            {% if author in edit_obj.author.all %}
            <option selected value="{{ author.pk }}">{{ author.name }}</option>
            {% else %}
            <option value="{{ author.pk }}">{{ author.name }}</option>
            {% endif %}
          {% endfor %}
        </select>
        </p>
        <input type="submit" class="btn btn-default">
      </form>
    </div>
  </div>
</div>
</body>
</html>

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

Python 相关文章推荐
在Python中使用itertools模块中的组合函数的教程
Apr 13 Python
Python中exit、return、sys.exit()等使用实例和区别
May 28 Python
python使用KNN算法手写体识别
Feb 01 Python
Python浅复制中对象生存周期实例分析
Apr 02 Python
Python cookbook(字符串与文本)在字符串的开头或结尾处进行文本匹配操作
Apr 20 Python
详解将Pandas中的DataFrame类型转换成Numpy中array类型的三种方法
Jul 06 Python
python判断一个对象是否可迭代的例子
Jul 22 Python
python线程的几种创建方式详解
Aug 29 Python
如何运行带参数的python脚本
Nov 15 Python
opencv resize图片为正方形尺寸的实现方法
Dec 26 Python
如何使用Python处理HDF格式数据及可视化问题
Jun 24 Python
使用numpy实现矩阵的翻转(flip)与旋转
Jun 03 Python
Python enumerate函数遍历数据对象组合过程解析
Dec 11 #Python
django框架基于queryset和双下划线的跨表查询操作详解
Dec 11 #Python
django框架ModelForm组件用法详解
Dec 11 #Python
django框架中ajax的使用及避开CSRF 验证的方式详解
Dec 11 #Python
通过实例解析Python调用json模块
Dec 11 #Python
Flask中endpoint的理解(小结)
Dec 11 #Python
Python中Flask-RESTful编写API接口(小白入门)
Dec 11 #Python
You might like
用PHP获取Google AJAX Search API 数据的代码
2010/03/12 PHP
在WAMP环境下搭建ZendDebugger php调试工具的方法
2011/07/18 PHP
PHP return语句的另一个作用
2014/07/30 PHP
php语言的7种基本的排序方法
2020/12/28 PHP
深入浅析yii2-gii自定义模板的方法
2016/04/26 PHP
PHP链表操作简单示例
2016/10/15 PHP
PHP实现的统计数据功能详解
2016/12/06 PHP
PHP常用函数之格式化时间操作示例
2019/10/21 PHP
自定义jQuery选项卡插件实例
2013/03/27 Javascript
jquery 图片缩放拖动的简单实例
2014/01/08 Javascript
js或jquery实现页面打印可局部打印
2014/03/27 Javascript
javascript相关事件的几个概念
2015/05/21 Javascript
javascript实现鼠标移到Image上方时显示文字效果的方法
2015/08/07 Javascript
JavaScript的jQuery库中ready方法的学习教程
2015/08/14 Javascript
JavaScript模拟数组合并concat
2016/03/06 Javascript
Jquery修改image的src属性,图片不加载问题的解决方法
2016/05/17 Javascript
Angularjs+bootstrap+table多选(全选)支持单击行选中实现编辑、删除功能
2017/03/27 Javascript
详解Vue中使用Echarts的两种方式
2018/07/03 Javascript
[07:06]2018DOTA2国际邀请赛寻真——卫冕冠军Team Liquid
2018/08/10 DOTA
python将人民币转换大写的脚本代码
2013/02/10 Python
Python通过DOM和SAX方式解析XML的应用实例分享
2015/11/16 Python
Python比较2个时间大小的实现方法
2018/04/10 Python
Matplotlib 生成不同大小的subplots实例
2018/05/25 Python
Pandas 同元素多列去重的实例
2018/07/03 Python
解决pycharm每次新建项目都要重新安装一些第三方库的问题
2019/01/17 Python
对Python3 序列解包详解
2019/02/16 Python
详解Python3序列赋值、序列解包
2019/05/14 Python
python二进制文件的转译详解
2019/07/03 Python
wxPython绘图模块wxPyPlot实现数据可视化
2019/11/19 Python
Oakley官网:运动太阳镜、雪镜和服装
2016/09/30 全球购物
英国户外服装品牌:Craghoppers
2019/04/25 全球购物
财务会计人员岗位职责
2013/11/30 职场文书
通信研究生自荐信
2014/02/01 职场文书
大队干部竞选演讲稿
2014/04/28 职场文书
《艾尔登法环》发布最新「战技」宣传片
2022/04/03 其他游戏
python三子棋游戏
2022/05/04 Python