欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

django框架兩個使用模板實例

 更新時間:2019年12月11日 11:56:43   作者:dawn-liu  
這篇文章主要介紹了django框架使用模板方法,結(jié)合兩個具體實例形式詳細(xì)分析了Django框架模板的相關(guān)使用技巧與操作注意事項,需要的朋友可以參考下

本文實例講述了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建立一對一的關(guān)系
  # ad=models.ForeignKey(to="AuthorDetail",to_field="id",on_delete=models.CASCADE,unique=True)
  #OneToOneField 表示創(chuàng)建一對一關(guān)系。on_delete=models.CASCADE 表示級聯(lián)刪除。假設(shè)a表刪除了一條記錄,b表也還會刪除對應(yīng)的記錄
  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),#這一條不能放上面,會造成死循環(huán)
  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("沒有書籍,請?zhí)砑訒?);window.location.href="/books/add" rel="external nofollow" rel="external nofollow" </script>'
    hint='<script>alert("沒有書籍,請?zhí)砑訒?);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("沒有書籍,請?zhí)砑訒?);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跳轉(zhuǎn)
    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跳轉(zhuǎn)
  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"  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  rel="external nofollow" >查看書籍</a></div>
        <div class="panel-body">
          Panel content
        </div>
      </div>
      <div class="panel panel-success">
        <div class="panel-heading"><a  rel="external nofollow" >添加書籍</a></div>
        <div class="panel-body">
          Panel content
        </div>
      </div>
      <div class="panel panel-warning">
        <div class="panel-heading"><a  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使用一對多和多對多關(guān)系建表之后的增刪改查

-------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()默認(rèn)級聯(lián)刪除
  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
    #綁定書籍與出版社一對多的關(guān)系
    obj=Book.objects.create(title=title,price=price,create_time=date,publish_id=publish_id)
    #綁定書籍與作者多對多的關(guān)系
    obj.author.add(*author_id_list)
    # obj.author.remove(1,2) #解除關(guān)系
    # obj.author.clear() #清空所有關(guān)系
    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) #相當(dāng)于上面兩條
    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">添加數(shù)據(jù)</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程序設(shè)計有所幫助。

相關(guān)文章

  • Python常用編譯器原理及特點解析

    Python常用編譯器原理及特點解析

    這篇文章主要介紹了Python常用編譯器原理及特點解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-03-03
  • Python批量刪除mysql中千萬級大量數(shù)據(jù)的腳本分享

    Python批量刪除mysql中千萬級大量數(shù)據(jù)的腳本分享

    這篇文章主要介紹了Python批量刪除mysql中千萬級大量數(shù)據(jù)的示例代碼,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2020-12-12
  • 對python中不同模塊(函數(shù)、類、變量)的調(diào)用詳解

    對python中不同模塊(函數(shù)、類、變量)的調(diào)用詳解

    今天小編就為大家分享一篇對python中不同模塊(函數(shù)、類、變量)的調(diào)用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • keras模型保存為tensorflow的二進(jìn)制模型方式

    keras模型保存為tensorflow的二進(jìn)制模型方式

    這篇文章主要介紹了keras模型保存為tensorflow的二進(jìn)制模型方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • Python函數(shù)之zip函數(shù)的介紹與實際應(yīng)用

    Python函數(shù)之zip函數(shù)的介紹與實際應(yīng)用

    zip() 函數(shù)用于將可迭代的對象作為參數(shù),將對象中對應(yīng)的元素打包成一個個元組,然后返回由這些元組組成的對象(python2 返回的是這些元組組成的列表 ),下面這篇文章主要給大家介紹了關(guān)于Python函數(shù)之zip函數(shù)實際應(yīng)用的相關(guān)資料,需要的朋友可以參考下
    2022-03-03
  • Python實現(xiàn)日志實時監(jiān)測的示例詳解

    Python實現(xiàn)日志實時監(jiān)測的示例詳解

    觀察者模式:是一種行為型設(shè)計模式。主要關(guān)注的是對象的責(zé)任,允許你定義一種訂閱機(jī)制,可在對象事件發(fā)生時通知多個"觀察"該對象的其他對象。本文將利用觀察者模式實現(xiàn)日志實時監(jiān)測,需要的可以參考一下
    2022-04-04
  • Python中json庫的操作指南

    Python中json庫的操作指南

    JSON是存儲和交換文本信息的語法,類似XML,JSON比XML更小、更快,更易解析,且易于人閱讀和編寫,下面這篇文章主要給大家介紹了關(guān)于Python中json庫的操作指南,需要的朋友可以參考下
    2023-04-04
  • python?使用第三方庫requests-toolbelt?上傳文件流的示例

    python?使用第三方庫requests-toolbelt?上傳文件流的示例

    這篇文章主要介紹了python?使用第三方庫requests-toolbelt?上傳文件流,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-09-09
  • python openpyxl方法 zip函數(shù)用法及說明

    python openpyxl方法 zip函數(shù)用法及說明

    這篇文章主要介紹了python openpyxl方法 zip函數(shù)用法及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • Python數(shù)據(jù)持久化shelve模塊用法分析

    Python數(shù)據(jù)持久化shelve模塊用法分析

    這篇文章主要介紹了Python數(shù)據(jù)持久化shelve模塊用法,結(jié)合實例形式較為詳細(xì)的總結(jié)分析了shelve模塊的功能、原理及簡單使用方法,需要的朋友可以參考下
    2018-06-06

最新評論