django框架两个使用模板实例

本文实例讲述了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使用一对多和多对多关系建表之后的增删改查

-------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程序设计有所帮助。

(0)

相关推荐

  • Django模板变量如何传递给外部js调用的方法小结

    前言 因为工作的需要,最近一直在思考如何更好的组织Django中的静态资源,比如JS.CSS一类,如何结合前端构建工具写出更好的代码以及结构呢?下面这篇文章就给大家详细介绍了实现的方法,话不多说,来一起看看详细的介绍: 方法如下: 首先需要解决的一个问题就是某些时候需要把JS代码写在模板里来获取后台传递过来的变量,比如: <div> <h1>Test</h1> <div id="my-test" ></div> </di

  • python Django模板的使用方法(图文)

    模版基本介绍模板是一个文本,用于分离文档的表现形式和内容. 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签). 模板通常用于产生HTML,但是Django的模板也能产生任何基于文本格式的文档.来一个项目说明1.建立MyDjangoSite项目具体不多说,参考前面.2.在MyDjangoSite(包含四个文件的)文件夹目录下新建templates文件夹存放模版.3.在刚建立的模版下建模版文件user_info.html 复制代码 代码如下: <html>    <

  • python+django加载静态网页模板解析

    接着前面Django入门使用示例 今天我们来看看Django是如何加载静态html的? 我们首先来看一看什么是静态HTML,什么是动态的HTML?二者有什么区别? 静态HTML指的是使用单纯的HTML或者结合CSS制作的包括图片.文字等的只供用户浏览但不包含任何脚本.不含有任何交互功能的网页! 动态的HTML指的是网页不仅提供给用户浏览,网页本身还有交互功能,存在着在脚本如JAVASCRIPT,并利用某种服务器端语言如PHP等实现如用户注册,用户登录,上传文件,下载文件等功能 接下来,了解下加载

  • 更换Django默认的模板引擎为jinja2的实现方法

    本机环境 操作系统:fedora24 python版本:3.5 Django版本:1.11.1 jinja2版本:2.9.6 为何要更换 DTL 先来谈谈Django的模板引擎,找了下,并没有一个确定的名字,就简单的叫Django Templates Language(DTL),中文就叫Django模板语言.使用中,大家会发现很多局限性,最明显的就是四则运算.就只能加减,乘除都不支持.另外还有判断相等,不能直接if,要用ifequal.确实不太方便.还有一点,DTL很慢,jinja2宣称比DTL

  • Python的Django框架中模板碎片缓存简介

    你同样可以使用cache标签来缓存模板片段. 在模板的顶端附近加入{% load cache %}以通知模板存取缓存标签. 模板标签{% cache %}在给定的时间内缓存了块的内容. 它至少需要两个参数: 缓存超时时间(以秒计)和指定缓存片段的名称. 示例: {% load cache %} {% cache 500 sidebar %} .. sidebar .. {% endcache %} 有时你可能想缓存基于片段的动态内容的多份拷贝. 比如,你想为上一个例子的每个用户分别缓存侧边栏.

  • 利用django-suit模板添加自定义的菜单、页面及设置访问权限

    前言 本文主要给大家介绍了利用django-suit模板在管理后台添加自定义的菜单和自定义的页面.设置访问权限的相关内容,分享出来供大家参考学习,下面话不多说了,来随着小编一起看看详细的介绍吧  方法如下: 1.先在settings.py里面的SUIT_CONFIG中添加配置,我们平时添加的配置都是app类型的,我们需要自定义页面的话,就不能用app了,需要用url,这里面我们使用如下: # django-suit config SUIT_CONFIG = { 'ADMIN_NAME': 'X·

  • 详解Django框架中用context来解析模板的方法

    你需要一段context来解析模板. 一般情况下,这是一个 django.template.Context 的实例,不过在Django中还可以用一个特殊的子类, django.template.RequestContext ,这个用起来稍微有些不同. RequestContext 默认地在模板context中加入了一些变量,如 HttpRequest 对象或当前登录用户的相关信息. 当你不想在一系例模板中都明确指定一些相同的变量时,你应该使用 RequestContext . 例如,考虑这两个视

  • 在Django框架中自定义模板过滤器的方法

    自定义过滤器就是有一个或两个参数的Python函数: (输入)变量的值 参数的值, 可以是默认值或者完全留空 例如,在过滤器 {{ var|foo:"bar" }} 中 ,过滤器 foo 会被传入变量 var 和默认参数 bar. 过滤器函数应该总有返回值. 而且不能触发异常,它们都应该静静地失败. 如果出现错误,应该返回一个原始输入或者空字符串,这会更有意义. 这里是一些定义过滤器的例子: def cut(value, arg): "Removes all values o

  • 使用grappelli为django admin后台添加模板

    grappelli是github上面star最多的django模板系统 http://django-grappelli.readthedocs.org/en/latest/quickstart.html#installation 复制代码 代码如下: pip install django-grappelli settings.py INSTALLED_APPS = (     'grappelli',     'django.contrib.admin', ) 添加url项 复制代码 代码如下:

  • django模板加载静态文件的方法步骤

    加载静态文件 在一个网页中,不仅仅只有一个 html 骨架,还需要 css 样式文件, js 执行文件以及一些图片等.因此在 DTL 中加载静态文件是一个必须要解决的问题.在 DTL 中,使用 static 标签来加载静态文件.要使用 static 标签,首先需要 {% load static %} .加载静态文件的步骤如下: 首先确保 django.contrib.staticfiles 已经添加到 settings.INSTALLED_APPS 中. 确保在 settings.py 中设置了

  • python Django模板的使用方法

    模板是一个文本,用于分离文档的表现形式和内容. 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签). 模板通常用于产生HTML,但是Django的模板也能产生任何基于文本格式的文档. 来一个项目说明 1.建立MyDjangoSite项目具体不多说,参考前面. 2.在MyDjangoSite(包含四个文件的)文件夹目录下新建templates文件夹存放模版. 3.在刚建立的模版下建模版文件user_info.html <html> <meta http-equiv=

随机推荐