python-Django 增删改和分页

先看效果:

显示和分页的效果


添加的效果:



修改页面效果:



删除效果:js判断提示



这里的分页需要用到bootstrap_pagination,我这里偷懒,用到了

bootstrap_toolkit插件,可以自行下载,安装的时候,win+D

cmd找到安装python的的文件夹,然后

pip install django-bootstrap-toolkit

Django其实就是MTV架构,mvc我们都不陌生


Django的MTV模式本质上和MVC是一样的,也是为了各组件间保持松耦合关系,只是定义上有些许不同,Django的MTV分别是值:

M 代表模型(Model):负责业务对象和数据库的关系映射(ORM)。
T 代表模板 (Template):负责如何把页面展示给用户(html)。
V 代表视图(View):负责业务逻辑,并在适当时候调用Model和Template。

除了以上三层之外,还需要一个URL分发器,它的作用是将一个个URL的页面请求分发给不同的View处理,View再调用相应的Model和Template,MTV的响应模式如下所示:


1,Web服务器(中间件)收到一个http请求
2,Django在URLconf里查找对应的视图(View)函数来处理http请求
3,视图函数调用相应的数据模型来存取数据、调用相应的模板向用户展示页面
4,视图函数处理结束后返回一个http的响应给Web服务器
5,Web服务器将响应发送给客户端

 

这种设计模式关键的优势在于各种组件都是松耦合的。这样,每个由 Django驱动的Web应用都有着明确的目的,并且可独立更改而不影响到其它的部分。 
比如,开发者更改一个应用程序中的 URL 而不用影响到这个程序底层的实现。设计师可以改变 HTML页面的样式而不用接触Python代码。
数据库管理员可以重新命名数据表并且只需更改模型,无需从一大堆文件中进行查找和替换。

落到实处,Django的MTV模式相对应的python文件如下:


好,不啰嗦了,各位看官久等了,来点硬货!

①、看下整个项目的目录:


先要配置settings.py


红框框的,bootstrap_toolkit插件需要手动添加,hgo是app项目

②、urls.py就是配置路由的地方,这里也很重要,我这是在工程里面有个默认的urls.py,在app的hgo里面添加了urls.py,如果在创建app,就可以在添加urls.py,免得都写到工程里面的urls.py,会显得臃肿,之前文件都有讲到怎么在app里面设置urls.py和工程里面的urls.py的设置,这里直接上代码:

Higo/urls.py 工程里默认的

from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
     url(r'^', include('hgo.urls'))
]

Hgo/urls.py 在app项目里面自己添加的

from django.conf.urls import  url
from hgo import views
urlpatterns = [
     url(r'^show/$', views.hgo_list),
     url(r'^insert/$', views.hgo_insert,name="hgo_insert"),
     url(r'^del/$', views.delById,name="hgo_del"),
     url(r'^query/$', views.queryById,name="hgo_query"),
      url(r'^add/$', views.upById,name="hgo_add"),
]

③、models.py

from django.db import models

# Create your models here.
class  Stu(models.Model):
    name=models.CharField(max_length=50)
    gender=models.CharField(max_length=2)
    age=models.IntegerField()
    address=models.CharField(max_length=50)

由此可以知道我们的表的字段和类型,id是不用写出来的

④、手动添加了一个forms.py,由于要用到Django  

ModelForm

from django import forms
from hgo.models import Stu
class StuFrom(forms.ModelForm):
    class Meta:
        model= Stu
        exclude= ("id",)

注意缩进哦!

⑤、views.py 就是我们的写逻辑的地方

#coding=utf-8
from django.shortcuts import render
from django.shortcuts import render,render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.template.context import RequestContext
from django.views.decorators.csrf import csrf_exempt
# 添加Django自带的分页插件 paginator
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger

#包装csrf请求,避免django认为其实跨站攻击脚本
from django.views.decorators.csrf import csrf_exempt
from .models import Stu
from Higo.forms import StuFrom
# Create your views here.
#显示所有数据,并分页
def hgo_list(request):
    limit = 5  # 每页显示的记录数
    stus=Stu.objects.all()
    paginator = Paginator(stus, limit)  # 实例化一个分页对象
    page = request.GET.get('page')  # 获取页码
    try:
        stus = paginator.page(page)  # 获取某页对应的记录
    except PageNotAnInteger:  # 如果页码不是个整数
        stus = paginator.page(1)  # 取第一页的记录
    except EmptyPage:  # 如果页码太大,没有相应的记录
        stus = paginator.page(paginator.num_pages)  # 取最后一页的记录
    return  render_to_response("index.html",RequestContext(request,{"lines":stus}))

#添加的方法
def hgo_insert(requset):
    if requset.method=="POST":
            stu_form=StuFrom(requset.POST)
            if stu_form.is_valid():
               stu_form.save()
            return HttpResponseRedirect("/show/")
    else:
        return render(requset,"insert.html")



#删除的方法
def delById(request):
    id=request.GET["id"];
    str=Stu.objects.get(id=id)
    str.delete()
    return  HttpResponseRedirect("/show/")

#查看的方法
def queryById(request):
    id=request.GET["id"];
    if id=="":
        return HttpResponseRedirect("/show/")
    stuu=Stu.objects.get(id=id)
    return  render_to_response("curd.html",{"d":stuu})

#修改数据的方法
@csrf_exempt
def upById(request):
      id=request.POST["id"];
      print(id)
      name=request.POST["name"];
      gender=request.POST["gender"];
      age=request.POST["age"];
      address=request.POST["address"];
      st=Stu()
      if  len(id)  > 0 :
        st.id=id;
      st.age=age;
      st.name=name;
      st.gender=gender;
      st.address=address;
      st.save()
      return  HttpResponseRedirect("/show/")

以上几个标红的都是很重要的!

我在app项目里面创建了两个文件夹,分别为static和

Templates,static是装js,css的地方,templates是

装静态页面的地方!页面放置到根目录,之前的文章有提及

显示和分页的页面:index.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.css' %}">
    <script src="{% static 'bootstrap/js/jquery.min.js' %}"></script>
    <script src="{% static 'bootstrap/js/bootstrap.js' %}"></script>
    <script type="text/javascript">
        $(function(){
            $("a:contains('删除')").click(function(){
                if(confirm('你确定要删除吗?'))
                {
                    return true;
                }else
                {
                    return false;
                }
            });
        });
    </script>
    <style type="text/css">
           .pagination {
    height: 40px;
    margin: 20px 0;
}
.pagination ul {
    border-radius: 3px 3px 3px 3px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    display: inline-block;
    margin-bottom: 0;
    margin-left: 0;
}
.pagination li {
    display: inline;
}
.pagination a, .pagination span {
    -moz-border-bottom-colors: none;
    -moz-border-left-colors: none;
    -moz-border-right-colors: none;
    -moz-border-top-colors: none;
    background-color: #FFFFFF;
    border-color: #DDDDDD;
    border-image: none;
    border-style: solid;
    border-width: 1px 1px 1px 0;
    float: left;
    line-height: 38px;
    padding: 0 14px;
    text-decoration: none;
}
.pagination a:hover, .pagination .active a, .pagination .active span {
    background-color: #F5F5F5;
}
.pagination .active a, .pagination .active span {
    color: #999999;
    cursor: default;
}
.pagination .disabled span, .pagination .disabled a, .pagination .disabled a:hover {
    background-color: transparent;
    color: #999999;
    cursor: default;
}
.pagination li:first-child a, .pagination li:first-child span {
    border-left-width: 1px;
    border-radius: 3px 0 0 3px;
}
.pagination li:last-child a, .pagination li:last-child span {
    border-radius: 0 3px 3px 0;
}
.pagination-centered {
    text-align: center;
}
.pagination-right {
    text-align: right;
}
    </style>
</head>
<body>
   <button class="btn btn-primary" type="button" οnclick="location.href='{% url 'hgo_insert' %}'">添加用户信息</button>
    {% load bootstrap_toolkit %}
   {% block content %}
   <table class="table table-striped table-bordered">
       <caption>用户信息</caption>
        <thead class="table-bordered">
            <tr>
              <th>姓名</th>
              <th>性别</th>
              <th>年龄</th>
                <th>住址</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody class="table-bordered">
          {% for user in lines %}
            <tr class="table-bordered">
              <td>{{ user.name}}</td>
              <td>{{ user.gender }}</td>
              <td>{{ user.age}}</td>
                <td>{{user.address }}</td>
              <td>
                  <a href="/del?id={{user.id }}"  class="text-danger">删除</a>
                  <a href="/query/?id={{user.id }}"  class="text-primary">修改</a>
              </td>
            </tr>
        {% endfor %}
        </tbody>
   </table>
      {% bootstrap_pagination lines url="/show?page=1" align="center" size="large" %}

{% endblock %}
</body>
</html>

爽吧,这里   {%bootstrap_pagination lines url="/show?page=1"align="center"size="large"%}

一行代码搞定分页,但是不是bootstrap的分页效果,需要在添加css,上面有独立写的css就是分页按钮的样式

添加的页面:insert.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加数据</title>
     <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.css' %}">
     <script src="{% static 'bootstrap/js/jquery.min.js' %}"></script>
    <script src="{% static 'bootstrap/js/bootstrap.js' %}"></script>
    <style>
.col-center-block {
    float: none;
    display: block;
    margin-left: auto;
    margin-right: auto;
}
</style>
</head>
<body>
  <div class="container">
  <div class="row myCenter">
    <div class="col-xs-6 col-md-4 col-center-block">
    <form role="form-horizontal" method="post" action="{% url 'hgo_insert' %}">
        {% csrf_token %}
      <div class="form-group">
          <label for="name">姓名:</label>
          <div class="controls">
          <input type="text"  id="name" class="form-control" name="name" placeholder="请输入姓名" style="width: 300px">
              </div>
      </div>
        <div class="form-group">
            <label class="gender">性别:</label>
            <label class="checkbox-inline">
                <input type="radio" name="gender" id="gender1" value="男" checked="checked">男
            </label>
             <label class="checkbox-inline">
                <input type="radio" name="gender"  id="gender1" value="女">女
            </label>
        </div>

        <div class="form-group">
            <label for="age">年龄:</label>
             <div class="controls">
            <input type="text" name="age" class="form-control"  id="age" placeholder="请输入年龄:" style="width: 300px">
                 </div>
        </div>
        <div class="form-group">
            <label for="address">住址:</label>
             <div class="controls">
            <input type="text" id="address" class="form-control"  name="address" placeholder="请输入住址:" style="width: 300px">
                  </div>
        </div>
        <button class="btn btn-primary" type="submit">提交</button>
    </form>
        </div>
      </div>
      </div>
</body>
</html>

这里要注意的是  {%csrf_token %}这行代码,因为是post提及,必须要写!不然会报403错误哦!

修改的页面:curd.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>修改信息</title>
    <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.css' %}">
    <script src="{% static 'bootstrap/js/jquery.min.js' %}"></script>
    <script src="{% static 'bootstrap/js/bootstrap.js' %}"></script>
    <script type="text/javascript">
        $(function(){
            var g=$("#hids").val();
            if(g=="男")
            {
              $("#gender1").attr("checked",true);
            }else
            {
                $("#gender2").attr("checked",true);
            }
        })
    </script>
</head>
<body>
<div class="container">
<form action="{% url 'hgo_add' %}" method="post" role="form">
       {% csrf_token %}
        <input type="hidden" name="id"  value="{{ d.id }}" ><br/>
      <div class="form-group">
        <label class="control-label">姓名:  </label>
        <input class="form-control" type="text" name="name" value="{{ d.name  }}"/>
      </div>
      <div class="form-group">
        <label class="control-label">年龄:  </label>
        <input class="form-control" type="text" name="age" value="{{ d.age }}"/>
      </div>
         <input type="hidden" id="hids"  value="{{ d.gender }}" ><br/>
        <div class="form-group">
            <label class="gender">性别:</label>
            <label class="checkbox-inline">
                <input type="radio" name="gender" id="gender1" value="男" checked="checked">男
            </label>
             <label class="checkbox-inline">
                <input type="radio" name="gender"  id="gender2" value="女">女
            </label>
        </div>
        <div class="form-group">
        <label class="control-label">住址:  </label>
        <input class="form-control" type="text" name="address" value="{{ d.address }}"/>
      </div>
          <input type="submit" value="保存" class="btn btn-default "/>
</form>
</div>
</body>
</html>


可能大家也注意到一点,就是我这里用到了两个隐藏域,一般来说不建议使用,第一个隐藏域是绑定id的,另一个是绑定接收的性别的,然后在通过Jquery来实现单选按钮的选中!

每天进步一点点!明天的你感谢今天努力的自己!






  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值