编程学习网 > 编程语言 > Python > Python中django框架两个使用模板实例
2022
11-08

Python中django框架两个使用模板实例

今天编程学习网为大家讲解Python中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 %}

以上就是“Python中django框架两个使用模板实例”的详细内容,想要了解更多Python教程欢迎持续关注编程学习网

扫码二维码 获取免费视频学习资料

Python编程学习

查 看2022高级编程视频教程免费获取