您好,登錄后才能下訂單哦!
本文實例講述了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 %} <h4>查看書籍</h4> <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 %} <h4>添加書籍</h4> <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 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 %} <h4>管理書籍</h4> <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 %} <h4>修改書籍</h4> <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()默認級聯(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) #相當于上面兩條 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" > <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" > <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" > <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è)計有所幫助。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。