• python_22(Form-CRM)


    第1章 CRM
    1.1 建项目
    1.2 settings
    1.3 规范url
    1.4 公共的后台模板
    1.5 创建部门表
    1.6 建库移库
    1.7 母版继承
    1.7.1 导入static
    1.7.2 导入母版html
    1.7.3 继承语法
    第2章 部门
    2.1 depart_list
    2.1.1 列表url
    2.1.2 创建函数
    2.1.3 创建部门列表html
    2.2 depart_add
    2.2.1 crm.urls.py
    2.2.2 创建MOdelForm
    2.2.3 创建函数
    2.2.4 创建depart_form.html
    2.3 depart_del/depart_edit
    2.3.1 结构目录
    第3章 用户(一对多(增加MD5))
    3.1 user_list
    3.2 user_add
    3.3 user_edit/user_del
    第4章 课程(同部门略)
    第5章 班级(多对多)
    5.1 class_list
    5.2 class_add
    5.3 class_del/class_edit
    第6章 分页及MD5
    第7章 ModelForm
    7.1 功能
    7.2 生成html标签
    7.2.1 fields = '__all__'
    7.2.2 fields = ['title']
    7.2.3 exclude = ['title']
    7.3 instance

    第1章 CRM

    1.1 建项目

    python3 manage.py  appstart crm

    1.2 settings

    pytho22.settings.py

    INSTALLED_APPS = [

        'django.contrib.admin',

        'django.contrib.auth',

        'django.contrib.contenttypes',

        'django.contrib.sessions',

        'django.contrib.messages',

        'django.contrib.staticfiles',

        'crm.apps.CrmConfig',

    ]

    1.3 规范url

    python22.crm.urls.py

     from django.conf.urls import url,include

    from django.contrib import admin

    from crm.views import home

     

    urlpatterns = [

        url(r'^index/', home.index),

     

    ]

    python22.urls.py

    from django.conf.urls import url,include

    from django.contrib import admin

     

    urlpatterns = [

        url(r'^admin/', admin.site.urls),

        url(r'crm/', include('crm.urls')),

    ]

    crm.views.home.py

    from django.shortcuts import render

     

    # Create your views here.

    def index(request):

        return  render(request,'index.html')

    crm.templates.index.html

    <!DOCTYPE html>

    <html lang="en">

    <head>

        <meta charset="UTF-8">

        <title>CRM:index</title>

    </head>

    <body>

    <h1>CRM:index</h1>

    </body>

    </html>

    1.4 公共的后台模板

    模板的查找顺序,先找根目录,再由app注册的顺序查找

    1.5 创建部门表

    from django.db import models

     

    # Create your models here.

    class Department(models.Model):

        '''

        部门表

        '''

        title = models.CharField(verbose_name='部门表',max_length=32)

        #将返回的object转换为字符串

        def __str__(self):

            return self.title

    1.6 建库移库

    python3 manage.py makemigrations

    python3 manage.py migrate

    1.7 母版继承

    1.7.1 导入static

    1.7.2 导入母版html

    {% load staticfiles %}

    <!DOCTYPE html>

    <html lang="en">

    <head>

        <meta charset="UTF-8">

        <title>路飞学城</title>

        <link rel="shortcut icon" href="{% static 'imgs/luffy-study-logo.png' %} ">

        <link rel="stylesheet" href="{% static 'plugins/bootstrap/css/bootstrap.css' %} "/>

        <link rel="stylesheet" href="{% static 'plugins/font-awesome/css/font-awesome.css' %} "/>

        <link rel="stylesheet" href="{% static 'css/commons.css' %} "/>

        <link rel="stylesheet" href="{% static 'css/nav.css' %} "/>

        <style>

            body {

                margin: 0;

            }

     

            .no-radius {

                border-radius: 0;

            }

     

            .no-margin {

                margin: 0;

            }

     

            .pg-body > .left-menu {

                background-color: #EAEDF1;

                position: absolute;

                left: 1px;

                top: 48px;

                bottom: 0;

                220px;

                border: 1px solid #EAEDF1;

                overflow: auto;

            }

     

            .pg-body > .right-body {

                position: absolute;

                left: 225px;

                right: 0;

                top: 48px;

                bottom: 0;

                overflow: scroll;

                border: 1px solid #ddd;

                border-top: 0;

                font-size: 13px;

                min- 755px;

            }

     

            .navbar-right {

                float: right !important;

                margin-right: -15px;

            }

     

            .luffy-container {

                padding: 15px;

            }

     

            .left-menu .menu-body .static-menu {

     

            }

     

            .left-menu .menu-body .static-menu .icon-wrap {

                20px;

                display: inline-block;

                text-align: center;

            }

     

            .left-menu .menu-body .static-menu a {

                text-decoration: none;

                padding: 8px 15px;

                border-bottom: 1px solid #ccc;

                color: #333;

                display: block;

                background: #efefef;

                background: -webkit-gradient(linear, left bottom, left top, color-stop(0, #efefef), color-stop(1, #fafafa));

                background: -ms-linear-gradient(bottom, #efefef, #fafafa);

                background: -o-linear-gradient(bottom, #efefef, #fafafa);

                filter: progid:dximagetransform.microsoft.gradient(startColorStr='#e3e3e3', EndColorStr='#ffffff');

                -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#fafafa',EndColorStr='#efefef')";

                box-shadow: inset 0 1px 1px white;

            }

     

            .left-menu .menu-body .static-menu a:hover {

                color: #2F72AB;

                border-left: 2px solid #2F72AB;

            }

     

            .left-menu .menu-body .static-menu a.active {

                color: #2F72AB;

                border-left: 2px solid #2F72AB;

            }

        </style>

        {% block css %} {% endblock %}

    </head>

    <body>

     

    <div class="pg-header">

        <div class="nav">

            <div class="logo-area left">

                <a href="#">

                    <img class="logo" src="{% static 'imgs/logo.svg' %}">

                    <span style="font-size: 18px;">路飞学城 </span>

                </a>

            </div>

     

            <div class="left-menu left">

                <a class="menu-item">资产管理</a>

                <a class="menu-item">用户信息</a>

                <a class="menu-item">路飞管理</a>

                <div class="menu-item">

                    <span>使用说明</span>

                    <i class="fa fa-caret-down" aria-hidden="true"></i>

                    <div class="more-info">

                        <a href="#" class="more-item">管他什么菜单</a>

                        <a href="#" class="more-item">实在是编不了</a>

                    </div>

                </div>

            </div>

     

            <div class="right-menu right clearfix">

     

                <div class="user-info right">

                    <a href="#" class="avatar">

                        <img class="img-circle" src="{% static 'imgs/default.png' %}">

                    </a>

     

                    <div class="more-info">

                        <a href="#" class="more-item">个人信息</a>

                        <a href="#" class="more-item">注销</a>

                    </div>

                </div>

     

                <a class="user-menu right">

                    消息

                    <i class="fa fa-commenting-o" aria-hidden="true"></i>

                    <span class="badge bg-success">2</span>

                </a>

     

                <a class="user-menu right">

                    通知

                    <i class="fa fa-envelope-o" aria-hidden="true"></i>

                    <span class="badge bg-success">2</span>

                </a>

     

                <a class="user-menu right">

                    任务

                    <i class="fa fa-bell-o" aria-hidden="true"></i>

                    <span class="badge bg-danger">4</span>

                </a>

            </div>

     

        </div>

    </div>

    <div class="pg-body">

        <div class="left-menu">

            <div class="menu-body">

                <div class="static-menu">

                    <a href="/crm/depart/list/"><span class="icon-wrap"><i class="fa fa-map-o" aria-hidden="true"></i></span> 部门管理</a>

                </div>

            </div>

        </div>

        <div class="right-body">

            <div>

                <ol class="breadcrumb no-radius no-margin" style="border-bottom: 1px solid #ddd;">

     

                    <li><a href="#">首页</a></li>

                    <li class="active">客户管理</li>

     

                </ol>

            </div>

            {% block content %} {% endblock %}

        </div>

    </div>

     

     

    <script src="{% static 'js/jquery-3.3.1.min.js' %} "></script>

    <script src="{% static 'plugins/bootstrap/js/bootstrap.js' %} "></script>

    {% block js %} {% endblock %}

    </body>

    </html>

    1.7.3 继承语法

    {% extends 'layout.html' %}

     

    {% block content %}

     

    <!DOCTYPE html>

    <html lang="en">

    <head>

        <meta charset="UTF-8">

        <title>CRM:index</title>

    </head>

    <body>

    <h1>CRM:index</h1>

    </body>

    </html>

     

    {% endblock %}

    第2章 部门

    2.1 depart_list

    2.1.1 列表url

    crm.urls.py

    from django.conf.urls import url,include

    from django.contrib import admin

    from crm.views import home

    from crm.views import  depart

     

    urlpatterns = [

        url(r'^index/', home.index),

        url(r'^depart/list/', depart.depart_list)

    2.1.2 创建函数

    crm.views.depart.py

    from django.shortcuts import  render

     

    def depart_list(request):

        return render(request,'depart_list.html')

                                                        

    2.1.3 创建部门列表html

    crm.templates.depart_html

    {% extends 'layout.html' %}

     

    {% block content %}

        <div style="margin: 5px;">

            <a href="/crm/depart/add/" class="btn btn-primary"><i class="fa fa-plus-circle" aria-hidden="true"></i> 添加</a>

        </div>

        <table class="table table-bordered">

            <thead>

                <tr>

                    <th>ID</th>

                    <th>名称</th>

                    <th>操作</th>

                </tr>

            </thead>

            <tbody>

                {% for row in depart_queryset %}

                    <tr>

                        <td>{{ row.id }}</td>

                        <td>{{ row.title }}</td>

                        <td>

                            <a href="/crm/depart/edit/{{ row.id }}/"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a>

                            |

                            <a href="/crm/depart/del/{{ row.id }}/" style="color: red;"><i class="fa fa-trash-o" aria-hidden="true"></i></a>

                        </td>

                    </tr>

                {% endfor %}

            </tbody>

        </table>

        <nav aria-label="Page navigation">

      <ul class="pagination">

          {{ pager.page_html|safe }}

      </ul>

    </nav>

    {% endblock %}

    2.2 depart_add

    2.2.1 crm.urls.py

    urlpatterns = [

        url(r'^index/$', home.index),

        url(r'^depart/list/$', depart.depart_list),

        url(r'^depart/add/$', depart.depart_add),

     ]

    2.2.2 创建MOdelForm

    crm.forms.depart.py

    from  crm  import  models

    from  django.forms import ModelForm

    from django import forms

     

     

    class DepartModelForm(ModelForm):

        class Meta:

            model =  models.Department

            fields = '__all__'

            widgets = {

                'title': forms.TextInput(attrs={'class':'form-control','placeholder':'部门名称'})

     

            }

            error_messages ={

                'title':{

                    'required':'部门名称不能为空'

                }

            }

    2.2.3 创建函数

    crm.views.depart.py

    def depart_add(request):

        '''

        添加部门

        :param request:

        :return:

        '''

        #批量创建部门

        # for  i  in  range(103):

        #     title = '部门-%s' %i

        #     models.Department.objects.create(title=title)

        if request.method == 'GET':

            form = DepartModelForm()

            return  render(request,'depart_add.html',{'form':form})

        form = DepartModelForm(data=request.POST)

        if form.is_valid():

            form.save()

            return redirect('/crm/depart/list/')

        return render(request,'depart_form.html',{'form':form})

    2.2.4 创建depart_form.html

    crm.templates

    {% extends 'layout.html' %}

     

    {% block content %}

        <form class="form-horizontal" method="post" novalidate>

            {% csrf_token %}

            <div class="form-group">

                <label class="col-sm-2 control-label">{{ form.title.label }}</label>

                <div class="col-sm-10">

                    {{ form.title }}

                    <span style="color: red;">{{ form.title.errors.0 }}</span>

                </div>

            </div>

            <div class="form-group">

                <div class="col-sm-offset-2 col-sm-10">

                    <input type="submit" class="btn btn-primary" value="提 交">

                </div>

            </div>

        </form>

    {% endblock %}

    2.3 depart_del/depart_edit

    crm.urls.py

        url(r'^depart/edit/(d+)/$', depart.depart_edit),

        url(r'^depart/del/(d+)/$', depart.depart_del),

    crm.views.depart.py

    def depart_edit(request,nid):

        '''

        编辑

        :param request:

        :return:

        '''

        obj = models.Department.objects.filter(id=nid).first()

        if request.method == 'GET':

            form = DepartModelForm(instance=obj)

            return render(request,'depart_form.html',{'form':form})

        form = DepartModelForm(data=request.POST,instance=obj)

        if form.is_valid():

            form.save()

            return  redirect('/crm/depart/list/')

        return  render(request,'depart_form.html',{'form':form})

     

    @login_required

    def  depart_del(request,nid):

        models.Department.objects.filter(id=nid).delete()

        return redirect('/crm/depart/list')

    2.3.1 结构目录

      

    第3章 用户(一对多(增加MD5))

    3.1 user_list

    crm.models.py

    class UserInfo(models.Model):

        """

        员工表

        """

        username = models.CharField(verbose_name='用户名',max_length=32)

        password = models.CharField(verbose_name='密码',max_length=64)

        email = models.EmailField(verbose_name='邮箱',max_length=128)

        gender_choices = (

            (1,'男'),

            (2,'女'),

        )

        gender = models.IntegerField(verbose_name='性别',choices=gender_choices)

        depart = models.ForeignKey(verbose_name='所在部门',to='Department')

     

        def __str__(self):

            return self.username

    crm.urls.py

    url(r'^user/list/$', user.user_list),

    crm.views.user.py

    from  crm.forms.user import  UserModelForm

    from  crm import models

    from basic.pager import Pagination

    from crm.views.login  import login_required

    from basic.md5_mode import md5

     

    @login_required

    def user_list(request):

        '''

        用户列表

        :param request:

        :return:

        '''

        page = request.GET.get('page', 1)  # 要查看的页码

        total_count = models.UserInfo.objects.all().count()  # 数据库中数据总条数

        pager = Pagination(page, total_count, '/crm/user/list/')

        user_queryset = models.UserInfo.objects.all()[pager.start:pager.end]

        return render(request, 'user_list.html', {'user_queryset': user_queryset, 'pager': pager})

    crm.templates.user_list.html

    {% extends 'layout.html' %}

     

    {% block content %}

        <div style="margin: 5px;">

            <a href="/crm/user/add/" class="btn btn-primary"><i class="fa fa-plus-circle" aria-hidden="true"></i> 添加</a>

        </div>

        <table class="table table-bordered">

            <thead>

                <tr>

                    <th>ID</th>

                    <th>姓名</th>

                    <th>密码</th>

                    <th>邮箱</th>

                    <th>性别</th>

                    <th>所属部门</th>

                    <th>操作</th>

                </tr>

            </thead>

            <tbody>

                {% for row in user_queryset %}

                    <tr>

                        <td>{{ row.id }}</td>

                        <td>{{ row.username }}</td>

                        <td>{{ row.password }}</td>

                        <td>{{ row.email }}</td>

    {#性别选择,数据库中写好的选择方式,可直接由django调用#}

                        <td>{{ row.get_gender_display }}</td>

    {#针对多表#}

                        <td>{{ row.depart.title }}</td>

                        <td>

                            <a href="/crm/user/edit/{{ row.id }}"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a>

                            |

                            <a href="/crm/user/del/{{ row.id }}" style="color: red;"><i class="fa fa-trash-o" aria-hidden="true"></i></a>

                        </td>

                    </tr>

                {% endfor %}

            </tbody>

        </table>

        <nav aria-label="Page navigation">

      <ul class="pagination">

          {{ pager.page_html|safe }}

      </ul>

        </nav>

    {% endblock %}

    3.2 user_add

    crm.urls.py

    url(r'^user/add/$', user.user_add),

    crm.forms.user.py

    from django import forms

    from  crm import models

     

    class UserModelForm(forms.ModelForm):

        class Meta:

            model =  models.UserInfo

            fields = '__all__'

            widgets = {

                'username': forms.TextInput(attrs={'class':'form-control','placeholder':'用户名'}),

                'password': forms.TextInput(attrs={'class':'form-control','placeholder':'密码'}),

                'email': forms.EmailInput(attrs={'class':'form-control','placeholder':'邮箱'}),

                'gender': forms.Select(attrs={'class':'form-control'}),

                'depart': forms.Select(attrs={'class':'form-control'}),

     

            }

            error_messages ={

                'email':{

                    'required':'邮箱地址不能为空',

                    'invalid':'邮箱的格式错误',

                },

                'username':{

                    'required':'用户名称不能为空',

                    # 'invalid':'邮箱的格式错误',

                },

                'password':{

                    'required':'密码称不能为空',

                    # 'invalid':'邮箱的格式错误',

                },

     

                'gender': {

                    'required': '亲选择你的性别',

                    # 'invalid':'邮箱的格式错误',

                },

     

                'depart': {

                    'required': '请选择一个部门',

                    # 'invalid':'邮箱的格式错误',

                },

            }

    crm.views.user.py

    def user_add(request):

        '''

        增加用户

        :param request:

        :return:

        '''

        if request.method == 'GET':

            form  = UserModelForm()

            return render(request,'user_form.html',{'form':form})

        form = UserModelForm(data=request.POST)

        if form.is_valid():

            username = form.cleaned_data['username']

            pwd = form.cleaned_data['password']

            email = form.cleaned_data['email']

            gender = form.cleaned_data['gender']

            depart = form.cleaned_data['depart']

            md5pwd = md5(username,pwd)

            models.UserInfo.objects.get_or_create(password=md5pwd,username=username,email=email,gender=gender,depart=depart)

            # form.save()

            return redirect('/crm/user/list')

        return render(request,'user_form.html',{'form':form})

    crm.templates.user_form.html

    {% extends 'layout.html' %}

     

    {% block content %}

        <form class="form-horizontal" method="post" novalidate>

            {% csrf_token %}

            {% for field in form %}

                <div class="form-group">

                    <label class="col-sm-2 control-label">{{ field.label }}</label>

                    <div class="col-sm-10">

                        {{ field }}

                        <span style="color: red;">{{ field.errors.0 }}</span>

                    </div>

                </div>

            {% endfor %}

            <div class="form-group">

                <div class="col-sm-offset-2 col-sm-10">

                    <input type="submit" class="btn btn-primary" value="提 交">

                </div>

            </div>

        </form>

    {% endblock %}

    3.3 user_edit/user_del

    def user_edit(request,nid):

        obj = models.UserInfo.objects.filter(id=nid).first()

        if request.method== 'GET':

            form = UserModelForm(instance=obj)

            return render(request,'user_form.html',{'form':form})

        form = UserModelForm(data=request.POST,instance=obj)

        if form.is_valid():

            form.save()

            return redirect('/crm/user/list/')

        return render(request,'user_form.html',{'form':form})

     

    def user_del(request,nid):

        models.UserInfo.objects.filter(id=nid).delete()

        return redirect('/crm/user/list/')

    第4章 课程(同部门略)

    第5章 班级(多对多)

    5.1 class_list

    crm.models.py

    class ClassList(models.Model):

        """

        班级表

        """

        course = models.ForeignKey(verbose_name='课程', to='Course')

        num = models.IntegerField(verbose_name='期')

        teachers = models.ManyToManyField(verbose_name='老师', to='UserInfo')

        def __str__(self):

            return self.course

    crm.urls.py

    url(r'^class/list/$', class_list.class_list),

    crm.views.class_list.py

    from django.shortcuts import  render,redirect

    from  crm.forms.class_list import  ClassModelForm

    from  crm import models

    from basic.pager import Pagination

    from crm.views.login  import login_required

     

    @login_required

    def class_list(request):

        '''

        课程列表

        :param request:

        :return:

        '''

        page = request.GET.get('page', 1)  # 要查看的页码

        total_count = models.ClassList.objects.all().count()  # 数据库中数据总条数

        pager = Pagination(page, total_count, '/crm/class/list/')

        class_queryset = models.ClassList.objects.values('id','course__title','num','teachers__username')[pager.start:pager.end]

        return render(request, 'class_list.html', {'class_queryset': class_queryset, 'pager': pager})

    crm.templates.class_list.html

    {% extends 'layout.html' %}

     

    {% block content %}

        <div style="margin: 5px;">

            <a href="/crm/class/add/" class="btn btn-primary"><i class="fa fa-plus-circle" aria-hidden="true"></i> 添加</a>

        </div>

        <table class="table table-bordered">

            <thead>

                <tr>

                    <th>ID</th>

                    <th>课程</th>

                    <th>期数</th>

                    <th>导师</th>

                    <th>操作</th>

                </tr>

            </thead>

            <tbody>

                {% for row in class_queryset %}

                    <tr>

                        <td>{{ row.id}}</td>

                        <td>{{ row.course__title}}</td>

                        <td>{{ row.num }}</td>

                        <td>{{ row.teachers__username}}</td>

                        <td>

                            <a href="/crm/class/edit/{{ row.id }}"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a>

                            |

                            <a href="/crm/class/del/{{ row.id }}" style="color: red;"><i class="fa fa-trash-o" aria-hidden="true"></i></a>

                        </td>

                    </tr>

                {% endfor %}

            </tbody>

        </table>

        <nav aria-label="Page navigation">

      <ul class="pagination">

          {{ pager.page_html|safe }}

      </ul>

        </nav>

    {% endblock %}

    5.2 class_add

    crm.urls.py

    url(r'^class/add/$', class_list.class_add),

    crm.views.class_list.py

    def class_add(request):

        '''

        增加班级

        :param request:

        :return:

        '''

        if request.method == 'GET':

            form  = ClassModelForm()

            return render(request,'class_form.html',{'form':form})

        form = ClassModelForm(data=request.POST)

        if form.is_valid():

            form.save()

            return redirect('/crm/class/list')

        return render(request,'class_form.html',{'form':form})

    crm.templates.class_form.html

    {% extends 'layout.html' %}

     

    {% block content %}

        <form class="form-horizontal" method="post" novalidate>

            {% csrf_token %}

            {% for field in form %}

                <div class="form-group">

                    <label class="col-sm-2 control-label">{{ field.label }}</label>

                    <div class="col-sm-10">

                        {{ field }}

                        <span style="color: red;">{{ field.errors.0 }}</span>

                    </div>

                </div>

            {% endfor %}

            <div class="form-group">

                <div class="col-sm-offset-2 col-sm-10">

                    <input type="submit" class="btn btn-primary" value="提 交">

                </div>

            </div>

        </form>

    {% endblock %}

    crom.forms.class_list.py

    from django import forms

    from  crm import models

     

    class ClassModelForm(forms.ModelForm):

        class Meta:

            model =  models.ClassList

            fields = '__all__'

     

            widgets = {

                'course': forms.Select(attrs={'class':'form-control'}),

                'num': forms.TextInput(attrs={'class':'form-control','placeholder':'期数'}),

                'teachers': forms.SelectMultiple(attrs={'class':'form-control'}),

     

            }

            error_messages ={

                'course':{

                    'required':'请至少选择一个课程',

                },

                'num':{

                    'required':'期数名称不能为空',

                },

                'teachers':{

                    'required':'请至少选择一名导师',

                },

     

                'gender': {

                    'required': '亲选择你的性别',

                    # 'invalid':'邮箱的格式错误',

                },

     

                'depart': {

                    'required': '请选择一个部门',

                    # 'invalid':'邮箱的格式错误',

                },

            }

    5.3 class_del/class_edit

    urls.py

    url(r'^class/edit/(d+)/$', class_list.class_edit),
    url(r'^class/add/(d+)/$', class_list.class_del),

    views.class.py

    def class_edit(request,nid):

        obj = models.ClassList.objects.filter(id=nid).first()

        if request.method== 'GET':

            form = ClassModelForm(instance=obj)

            return render(request,'class_form.html',{'form':form})

        form = ClassModelForm(data=request.POST,instance=obj)

        if form.is_valid():

            form.save()

            return redirect('/crm/class/list/')

        return render(request,'class_form.html',{'form':form})

     

     

    def class_del(request,nid):

        models.ClassList.objects.filter(id=nid).delete()

        return redirect('/crm/class/list/')

    第6章 分页及MD5

    python22.basic.md5.py

    import hashlib

     

    #MD5加密

    def md5(username,password):

        '''

        动态用户名加盐

        :param username:

        :param password:

        :return:

        使用方法:md5(username,password)

        '''

        md5_pwd = hashlib.md5(username.encode("utf-8"))

        md5_pwd.update(password.encode('utf-8'))

        #返回加密数据

        return md5_pwd.hexdigest()

    python22.pager.py

    """

    使用文档:

        1. 获取两个数据给Pagination

            - 数据库的数据总数据量

            - 当前要访问的页码

            例如:

                page = request.GET.get('page', 1) # 要查看的页码

                total_count = models.Department.objects.all().count() # 数据库中数据总条数

                pager = Pagination(page,total_count,'/crm/depart/list/')

        2. Pagination对象有两个功能

            - 计算数据切片索引

                例如:

                    depart_queryset = models.Department.objects.all()[pager.start :pager.end]

            - 生成页码HTMl

                例如:在页面中使用

                      <ul class="pagination">

                          {{ pager.page_html|safe }}

                      </ul>

    """

     

    class Pagination(object):

        """

        分页相关

        """

        def __init__(self,page,total_count,url, per_page_count=10,max_page_num=11):

            """

            :param page: 当前页

            :param total_count: 数据库中数据总条数

            :param url: 路径

            :param per_page_count: 页面显示的数据条数

            :param max_page_num:  最多显示的页码数量

            """

            try:

                page = int(page)

            except Exception as e:

                page =1

            if page <1:

                page = 1

            self.page = page

            self.total_count = total_count

            self.url = url

            self.per_page_count = per_page_count

            self.max_page_num = max_page_num

     

            self.half_max_page_num = int(max_page_num / 2)

            self.total_page_num, x = divmod(total_count, per_page_count)

            if x > 0:

                self.total_page_num += 1

        @property

        def start(self):

            return (self.page-1) * self.per_page_count

     

        @property

        def end(self):

            return self.page * self.per_page_count

     

        def page_html(self):

            # 如果数据库中的数据最多总共能到11条 10,9,0 < max_page_num

            if self.total_page_num <= self.max_page_num:

                page_start = 1

                page_end = self.total_page_num + 1

            else:

                # 如果当前访问的页码: 1,2,3,4,5

                if self.page <=self.half_max_page_num:

                    page_start = 1

                    page_end = self.max_page_num + 1

                else:

                    # 如果当前页+5 > 总页码

                    if self.page + self.half_max_page_num > self.total_page_num:

                        page_start = self.total_page_num - self.max_page_num + 1

                        page_end = self.total_page_num + 1

                    else:

                        page_start = self.page - self.half_max_page_num

                        page_end = self.page + self.half_max_page_num + 1

            pager_list = []

     

            # 上一页

            if self.page > 1:

                prev = '<li><a href="%s?page=%s">上一页</a></li>' % (self.url,self.page - 1,)

                pager_list.append(prev)

     

            for i in range(page_start, page_end):  # 应该显示一定范围的页码

                if i == self.page:

                    temp = '<li class="active"><a href="%s?page=%s">%s</a></li>' % (self.url,i, i,)

                else:

                    temp = '<li><a href="%s?page=%s">%s</a></li>' % (self.url,i, i,)

                pager_list.append(temp)

     

            # 下一页

            if self.page < self.total_page_num:

                nex = '<li><a href="%s?page=%s">下一页</a></li>' % (self.url,self.page + 1,)

                pager_list.append(nex)

     

            return "".join(pager_list)

    第7章 ModelForm

    7.1 功能

    l  生成用户提交请求的html标签

    l  提供用户提交请求校验方式

    7.2 生成html标签

    crm.forms.depart.py

    from  crm  import  models

    from  django.forms import ModelForm

    from django import forms

     

     

    class DepartModelForm(ModelForm):

    #固定写法

        class Meta:

            model =  models.Department

    #将数据库的值拿出来一个个进行对比校验

            fields = '__all__'

    #生成请求标签

            widgets = {

                'title': forms.TextInput(attrs={'class':'form-control','placeholder':'部门名称'})

     

            }

            error_messages ={

                'title':{

                    'required':'部门名称不能为空'

                }

            }

    html中的取值

    7.2.1 fields = '__all__'

    解释:全部进行比对校验

    7.2.2 fields = ['title']

    解释:只数据库中的title,进行对比

    7.2.3 exclude = ['title']

    解释:只对数据库中的title,进行排除

    7.3 instance

    携带默认值,数据库值出入form

    def depart_edit(request,nid):

        '''

        编辑

        :param request:

        :return:

        '''

        obj = models.Department.objects.filter(id=nid).first()

        if request.method == 'GET':

        #生成默认值+html标签,默认值包括obj所有数据

            form = DepartModelForm(instance=obj)

            return render(request,'depart_form.html',{'form':form})#return form带默认值

        form = DepartModelForm(data=request.POST,instance=obj)

        if form.is_valid():

            form.save()

            return  redirect('/crm/depart/list/')

        return  render(request,'depart_form.html',{'form':form})

  • 相关阅读:
    关于Action中ValidateXXX方法校验一次失败后\导致以后一直返回input视图的情况
    but has failed to stop it. This is very likely to create a memory leak(c3p0在Spring管理中,连接未关闭导致的内存溢出)
    个人学习笔记MyBatis的搭建及第一个程序
    Hibernate学习笔记环境搭建及运行
    个人学习笔记MyBatis官方推荐DAO开发方案
    个人笔记struts2对Action的权限拦截
    hession
    正向代理,反向代理
    path,classpath
    session
  • 原文地址:https://www.cnblogs.com/wang-xd/p/10384687.html
Copyright © 2020-2023  润新知