15分页器和form组件

【一】分页器的使用

(1)封装好的方法可以自己新建一个文件直接拿去用
class Pagination(object):
    def __init__(self, current_page, all_count, per_page_num=2, pager_count=11):
        """
        封装分页相关数据
        :param current_page: 当前页
        :param all_count:    数据库中的数据总条数
        :param per_page_num: 每页显示的数据条数
        :param pager_count:  最多显示的页码个数
        """
        try:
            current_page = int(current_page)
        except Exception as e:
            current_page = 1
 
        if current_page < 1:
            current_page = 1
 
        self.current_page = current_page
 
        self.all_count = all_count
        self.per_page_num = per_page_num
 
        # 总页码
        all_pager, tmp = divmod(all_count, per_page_num)
        if tmp:
            all_pager += 1
        self.all_pager = all_pager
 
        self.pager_count = pager_count
        self.pager_count_half = int((pager_count - 1) / 2)
 
    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_num
 
    @property
    def end(self):
        return self.current_page * self.per_page_num
 
    def page_html(self):
        # 如果总页码 < 11个:
        if self.all_pager <= self.pager_count:
            pager_start = 1
            pager_end = self.all_pager + 1
        # 总页码  > 11
        else:
            # 当前页如果<=页面上最多显示11/2个页码
            if self.current_page <= self.pager_count_half:
                pager_start = 1
                pager_end = self.pager_count + 1
 
            # 当前页大于5
            else:
                # 页码翻到最后
                if (self.current_page + self.pager_count_half) > self.all_pager:
                    pager_end = self.all_pager + 1
                    pager_start = self.all_pager - self.pager_count + 1
                else:
                    pager_start = self.current_page - self.pager_count_half
                    pager_end = self.current_page + self.pager_count_half + 1
 
        page_html_list = []
        # 添加前面的nav和ul标签
        page_html_list.append('''
                    <nav aria-label='Page navigation>'
                    <ul class='pagination'>
                ''')
        first_page = '<li><a href="?page=%s">首页</a></li>' % (1)
        page_html_list.append(first_page)
 
        if self.current_page <= 1:
            prev_page = '<li class="disabled"><a href="#">上一页</a></li>'
        else:
            prev_page = '<li><a href="?page=%s">上一页</a></li>' % (self.current_page - 1,)
 
        page_html_list.append(prev_page)
 
        for i in range(pager_start, pager_end):
            if i == self.current_page:
                temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,)
            else:
                temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,)
            page_html_list.append(temp)
 
        if self.current_page >= self.all_pager:
            next_page = '<li class="disabled"><a href="#">下一页</a></li>'
        else:
            next_page = '<li><a href="?page=%s">下一页</a></li>' % (self.current_page + 1,)
        page_html_list.append(next_page)
 
        last_page = '<li><a href="?page=%s">尾页</a></li>' % (self.all_pager,)
        page_html_list.append(last_page)
        # 尾部添加标签
        page_html_list.append('''
                                           </nav>
                                           </ul>
                                       ''')
        return ''.join(page_html_list)
(2)使用
1.先导入那个分页器文件
from utils import mypage
​
2.产生分页器对象
//获取所有数据库中数据的条数
book_queryset = models.Books.objects.all()
page_obj = mypage.Pagination(current_page=request.GET.get('page'),all_count=book_queryset.count())
​
3.产生分页数据对象
page_queryset=book_queryset[page_obj.start:page_obj.end]
return render(request,'many_data.html',locals())
​



前端
{% for book_obj in page_queryset %}
    <p>{{ book_obj.title }}</p>
{% endfor %}
{{ page_obj.page_html|safe }}

【二】Forms组件

(1)低配版校验用户名密码
"""编写一个校验用户名和密码是否合法的功能
    前端需要自己编写获取用户数据的各种标签
  前端需要自己想方设法的展示错误的提示信息
  后端需要自己想方设法的编写校验代码(很多if判断)"""
​
"""
后端有个检验的字典,没值前端的span就没有信息,有值就有信息
"""
1.前端:
 
<form action="" method="post">
    <p>username:
        <input type="text" class="form-control" name="username">
        <span style="color: red">{{ back_dict.username }}</span>
    </p>
    <p>password:
        <input type="password" class="form-control" name="password">
        <span style="color: red">{{ back_dict.password }}</span>
​
    </p>
    <input type="submit" class="btn btn-danger">
</form>
​
2.后端
from django.shortcuts import render
​
​
# Create your views here.
def register(request):
    back_dict = {}
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if "啦啦啦" in username:
            back_dict['username'] = '用户名不符合格式!'
        if len(password) < 3:
            back_dict['password'] = '输入的密码长度不够!'
​
        '''
        无论是 get 请求 还是 post 请求,页面都能获取到字典
            get 请求时,字典是空的,没有值
            post 请求时 ,字典可能是非空的
        '''
    return render(request, 'ab_form.html',locals())
(2)forms模块
# form组件
上面的三件事有一个人可以一次性帮你搞定>>>:form组件
  1.数据校验
  2.标签渲染
  3.展示信息
# 1.基本使用
from django import forms
class MyForm(forms.Form):
    # 用户名至少三个字符最多八个字符
    username = forms.CharField(min_length=3,max_length=8)
    # 年龄最小不能小于0 最大不能超过150
    age = forms.IntegerField(min_value=0,max_value=150)
    # 邮箱必须符合邮箱格式(@关键符号)
    email = forms.EmailField()
    
#2.校验数据
(1).将数据传入实例化对象
form_obj =MyForm({'username':'jason','age':18,'email':'123qq'})
(2).查看数据是否合法(全部合法结果才是True)
form_obj.is_valid()
(3).查看不符合条件的数据及原因
form_obj.errors
    {'email': ['Enter a valid email address.']}
(4).查看符合条件的数据
form_obj.cleaned_data
    {'username': 'jason', 'age': 18}
​
"""
1.forms类中所有的字段数据默认都是必填的 不能少
3.如果想忽略某些字段 可以添加参数  required=False
2.forms类中额外传入的字段数据不会做任何的校验 直接忽略
"""
(3)渲染标签
"""
print(f.as_table())
表一行的值
# <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required /><br /><span class="helptext">100 characters max.</span></td></tr>
# <tr><th>Message:</th><td><input type="text" name="message" required /></td></tr>
# <tr><th>Sender:</th><td><input type="email" name="sender" required /><br />A valid email address, please.</td></tr>
# <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
print(f.as_ul())
无序列表
# <li>Subject: <input type="text" name="subject" maxlength="100" required /> <span class="helptext">100 characters max.</span></li>
# <li>Message: <input type="text" name="message" required /></li>
# <li>Sender: <input type="email" name="sender" required /> A valid email address, please.</li>
# <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
print(f.as_p())
每个都是一行
# <p>Subject: <input type="text" name="subject" maxlength="100" required /> <span class="helptext">100 characters max.</span></p>
# <p>Message: <input type="text" name="message" required /></p>
# <p>Sender: <input type="email" name="sender" required /> A valid email address, please.</p>
# <p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
"""
渲染方式1:封装程度高 扩展性较差 主要用于快速生成页面测试功能
    {{ form_obj.as_p }}---》每个字段都是一个p标签然后username:输入框,一行一个字段名
  {{ form_obj.as_table }}变成一行
  {{ form_obj.as_ul }}链接前面有黑圆点
  
渲染方式2:封装程度低 扩展性较好 但是字段比较多的情况下不方便
  {{ form_obj.username.label }}  # 文本提示username
  {{ form_obj.username }}# 获取用户数据的标签input
  
渲染方式3:推荐使用!!!
  {% for form in form_obj %}
      <p>
        {{ form.label }}
        {{ form }}
      </p>
  {% endfor %}
"""
forms组件只负责渲染获取用户数据的标签
    form表单标签和提交按钮需要自己写
​
渲染标签中文提示 可以使用参数 label指定 不指定默认使用字段名首字母大写
"""
(4)展示信息
"""
forms类中填写的校验性参数前端浏览器会识别并添加校验操作
但是前端的校验是可有可无的 不能指望它!!!   后端必须要有
因为在检查中修改就可以不校验了
form表单可以取消浏览器自动添加校验功能的操作
    <form action="" method="post" novalidate>
    novalidate不让浏览器做任何校验,所有的校验让后端来做
    </form>
"""
{{ form.errors.0 }}有问题的数据,不写0是一个无序列表在输入框标签下面,写0就有了会在左侧提示,0就是取第一个错误信息
在前端标签下面
<span style="color: red">{{  form.errors.0 }}</span>和低配版的form提示一样
1.前端
<form action="" method="post" novalidate>
    {% for form in form_obj %}
      <p>
        {{ form.label }}
        {{ form }}
      <span style="color: red">{{ form.errors.0 }}</span>
      </p>
  {% endfor %}
<input type="submit">
</form>

2.后端:
 
def form(request):
    form_obj=MyForm()
    if request.method=='POST':
        form_obj=MyForm(request.POST)
        if form_obj.is_valid():
            return HttpResponse("数据没问题")
    return render(request, 'from.html',locals())    
3.提示信息可以自定义
from django import forms
class MyForm(forms.Form):
    username = forms.CharField(min_length=3, max_length=8, label='用户名',
                               error_messages={
                                   'min_length': '用户名最短3位',
                                   'max_length': '用户名最长8位',
                                   'required': '用户名必填'
                               }
​
                               )
    # 年龄最小不能小于0 最大不能超过150
    age = forms.IntegerField(min_value=0, max_value=150, label='年龄',
                             error_messages={
                                 'required': '用户名必填'
                             }
                             )
    # 邮箱必须符合邮箱格式(@关键符号)
    email = forms.EmailField(label='邮箱',
                             error_messages={
                                 'required': '用户名必填'
                             }                          })
(5)字段参数
 username = forms.CharField(
            # 【1】最大长度
            max_length=5,
            # 【2】最小长度
            min_length=3,
            # 【3】限制当前字段非必须传入
            # required=False,
            # 【4】label 就是前端显示在 input 输入框之前的提示文本
            label="用户名",
            # 【5】input 框内的默认值
            # initial="请输入用户名"
            # 【6】控制 提示内容和 input 框之间的 字符
            label_suffix="&",
            # 【7】控制前端样式
            widget=forms.widgets.TextInput(
                # attrs 可以放前端的 键值属性
                attrs={
                    'class': 'form-control',
                    # "id": "username",
                    "placeholder": "请输入用户名"
                }
            ),
            # 【8】显示在 input 框下面的注释文本
            help_text="用户名的注解文本",
            # 【9】存放错误信息
            error_messages={
                "required": "用户名必须传",
                "min_length": "你怎么吃的这么少!"
            },
            # 【10】不可选中状态
            disabled=True,
        )
    #【11】选择
       hobby = forms.ChoiceField(
            choices=((1, "篮球"), (2, "足球"), (3, "双色球"),),
            label="爱好",
            initial=3,
            widget=forms.widgets.Select()
        ) 

【三】自定义验证器

# 第一步 定义一个 Form 组件类
# 第二步 Form组件类继承 forms.Form
# 第三步 定义字段验证规则 forms.CharField()
# 第四步 定义一个验证函数 函数的参数就是 当前需要验证的值
# 第五步 将验证函数添加到上面的验证规则里面 forms.CharField(validators=[验证函数])
​
'''

def form_check(request):
    # 【场景】:我们有自己的规则需要对参数进行校验 ---> 自己主动写 验证器
    # 比如需要对手机号的格式进行验证的时候内置的验证规则是没有的!所以我们需要自己主动写
    import re
    from django.core.exceptions import ValidationError
    # 创建一个验证器函数
    def phone_validate(value):
        # print(f"phone_validate :>>> {value}")
        # phone_validate :>>> 15936369696
​
        # 手机号格式匹配规则
        mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
        # 通过 正则表达式对象匹配输入的内容
        if not mobile_re.match(value):
            # 抛出异常 ---> 会被 Form 组件捕获到
            raise ValidationError('手机号码格式错误')
​
    # 【1】先定义一个验证规则类
    class CheckForm(forms.Form):
        # 验证电话格式
        phone = forms.CharField(
            label="手机号",
            validators=[phone_validate]
        )
​
    form_obj = CheckForm({
        "phone": "159363696"
    })
    # 【1】先调用校验
    form_obj.is_valid()
    # 【2】获取到校验失败的数据
    print(form_obj.errors)
    # 【3】获取到校验成功的数据
    print(form_obj.cleaned_data)
​
    return render(request, 'forms_check.html', locals())
​
'''

【四】Form组件字段参数

1.min_length				最小长度
2.max_length				最大长度
3.label							字段名称
4.error_messages	  重写错误提示
5.min_value					最小值
6.max_value					最大值
7.initial						默认值
8.validators				正则校验器
eg:
"""
from django.core.validators import RegexValidator
  phone = forms.CharField(
        validators=[
                    RegexValidator(r'^[0-9]+$', '请输入数字'),
                    RegexValidator(r'^159[0-9]+$', '数字必须以159开头')],
    )
"""
9.widget						控制渲染出来的标签各项属性
1. forms.TextInput:默认的文本输入框小部件。
2. forms.Textarea:多行文本输入框小部件。
3. forms.CheckboxInput:复选框小部件。
4. forms.Select:下拉选择框小部件。
5. forms.RadioSelect:单选按钮小部件。
6. forms.FileInput:文件上传小部件。
7. forms.HiddenInput:隐藏输入框小部件。
eg:
"""
    密码变成密文
    password = forms.CharField(                          widget=forms.widgets.PasswordInput(attrs={'class':'form-control'})
)
forms.widgets.控制type的类型(attrs=控制各项属性:class id ...)
    """

10.radioSelect选择框--》单radio值为字符串
eg:"""
gender = forms.fields.ChoiceField(
        choices=((1, "男"), (2, "女"), (3, "保密")),
        label="性别",
        initial=3,
        widget=forms.widgets.RadioSelect()
    )
"""
11.Select单选框-->会有一个下拉菜单
eg:"""
hobby = forms.ChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ),
        label="爱好",
        initial=3,
        widget=forms.widgets.Select()
    )
"""
    
12.Select多选框    
eg:
    '''
hobby = forms.MultipleChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"),),
        label="爱好",
        initial=[1, 3],
        widget=forms.widgets.SelectMultiple()
    )
'''    
    
13.checkbox单选框 
 eg:
        """keep = forms.ChoiceField(
        label="是否记住密码",
        initial="checked",
        widget=forms.widgets.CheckboxInput()
    )"""

14 .checkbox多选框       
eg:"""
class LoginForm(forms.Form):
    ...
    hobby = forms.MultipleChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"),),
        label="爱好",
        initial=[1, 3],
        widget=forms.widgets.CheckboxSelectMultiple()
    )
"""        
        
        
(1)choice
from django.forms import Form
from django.forms import widgets
from django.forms import fields

 
class MyForm(Form):
 
    user = fields.ChoiceField(
        # choices=((1, '上海'), (2, '北京'),),
        initial=2,
        widget=widgets.Select
    )
 
    def __init__(self, *args, **kwargs):
        super(MyForm,self).__init__(*args, **kwargs)
        # self.fields['user'].choices = ((1, '上海'), (2, '北京'),)
        # 或
        self.fields['user'].choices = models.Classes.objects.all().values_list('id','caption')

【五】全局钩子和局部钩子

"""钩子函数的含义其实就是在程序的执行过程中穿插额外的逻辑

校验用户名是否已存在
	钩子函数之局部钩子(校验单个字段)

校验密码和确认密码是否一致
	钩子函数之全局钩子(校验多个字段)"""

"""
报错信息显示顺序:

先显示字段属性中的错误信息,然后再显示局部钩子的错误信息。
若显示了字段属性的错误信息,就不会显示局部钩子的错误信息。
若有全局钩子,则全局钩子是等所有的数据都校验完,才开始进行校验,并且全局钩子的错误信息一定会显示
"""
# 1.局部钩子:校验用户名是否已存在(一次性只能勾一个人)
    '''钩子函数是数据经过了字段第一层参数校验之后才会执行'''
    在myform类里写---》类似装饰器
def clean_name(self):  # 自动生成的函数名 专门用于对name字段添加额外的校验规则
        # 1.先获取用户名
        name = self.cleaned_data.get('name')
        # 2.判断用户名是否已存在
        is_exist = models.User.objects.filter(name=name)
        if is_exist:
            # 3.提示信息
            self.add_error('name', '用户名已存在')
        # 4.最后将你勾上来的name返回回去
        return name

    
    
# 2.全局钩子:校验密码与确认密码是否一致(一次性可以勾多个人)
def clean(self):
        # 1.获取多个字段数据
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if not password == confirm_password:
            self.add_error('confirm_password', '两次密码不一致 你个傻帽!!!')
        # 最后将整个数据返回
        return self.cleaned_data

【六】Django中的form所有内置字段

"""下面的类型,多注意:CharField、IntegerField、ChoiceField、EmailField、 DateField、TimeField、DateTimeField、FileField(文件上传)、ImageField(图像上传)"""
Field
    required=True,               是否允许为空
    widget=None,                 HTML插件
    label=None,                  用于生成Label标签或显示内容
    initial=None,                初始值
    help_text='',                帮助信息(在标签旁边显示)
    error_messages=None,         错误信息 {'required': '不能为空', 'invalid': '格式错误'}
    show_hidden_initial=False,   是否在当前插件后面再加一个隐藏的且具有默认值的插件(可用于检验两次输入是否一直)
    validators=[],               自定义验证规则
    localize=False,              是否支持本地化
    disabled=False,              是否可以编辑
    label_suffix=None            Label内容后缀
 
 
CharField(Field)
    max_length=None,             最大长度
    min_length=None,             最小长度
    strip=True                   是否移除用户输入空白
 
IntegerField(Field)
    max_value=None,              最大值
    min_value=None,              最小值
 
FloatField(IntegerField)
    ...
 
DecimalField(IntegerField)
    max_value=None,              最大值
    min_value=None,              最小值
    max_digits=None,             总长度
    decimal_places=None,         小数位长度
 
BaseTemporalField(Field)
    input_formats=None          时间格式化   
 
DateField(BaseTemporalField)    格式:2015-09-01
TimeField(BaseTemporalField)    格式:11:12
DateTimeField(BaseTemporalField)格式:2015-09-01 11:12
 
DurationField(Field)            时间间隔:%d %H:%M:%S.%f
    ...
 
RegexField(CharField)
    regex,                      自定制正则表达式
    max_length=None,            最大长度
    min_length=None,            最小长度
    error_message=None,         忽略,错误信息使用 error_messages={'invalid': '...'}
 
EmailField(CharField)      
    ...
 
FileField(Field)
    allow_empty_file=False     是否允许空文件
 
ImageField(FileField)      
    ...
    注:需要PIL模块,pip3 install Pillow
    以上两个字典使用时,需要注意两点:
        - form表单中 enctype="multipart/form-data"
        - view函数中 obj = MyForm(request.POST, request.FILES)
 
URLField(Field)
    ...
 
 
BooleanField(Field)  
    ...
 
NullBooleanField(BooleanField)
    ...
 
ChoiceField(Field)
    ...
    choices=(),                选项,如:choices = ((0,'上海'),(1,'北京'),)
    required=True,             是否必填
    widget=None,               插件,默认select插件
    label=None,                Label内容
    initial=None,              初始值
    help_text='',              帮助提示
 
 
ModelChoiceField(ChoiceField)
    ...                        django.forms.models.ModelChoiceField
    queryset,                  # 查询数据库中的数据
    empty_label="---------",   # 默认空显示内容
    to_field_name=None,        # HTML中value的值对应的字段
    limit_choices_to=None      # ModelForm中对queryset二次筛选
     
ModelMultipleChoiceField(ModelChoiceField)
    ...                        django.forms.models.ModelMultipleChoiceField
 
 
     
TypedChoiceField(ChoiceField)
    coerce = lambda val: val   对选中的值进行一次转换
    empty_value= ''            空值的默认值
 
MultipleChoiceField(ChoiceField)
    ...
 
TypedMultipleChoiceField(MultipleChoiceField)
    coerce = lambda val: val   对选中的每一个值进行一次转换
    empty_value= ''            空值的默认值
 
ComboField(Field)
    fields=()                  使用多个验证,如下:即验证最大长度20,又验证邮箱格式
                               fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])
 
MultiValueField(Field)
    PS: 抽象类,子类中可以实现聚合多个字典去匹配一个值,要配合MultiWidget使用
 
SplitDateTimeField(MultiValueField)
    input_date_formats=None,   格式列表:['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y']
    input_time_formats=None    格式列表:['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
 
FilePathField(ChoiceField)     文件选项,目录下文件显示在页面中
    path,                      文件夹路径
    match=None,                正则匹配
    recursive=False,           递归下面的文件夹
    allow_files=True,          允许文件
    allow_folders=False,       允许文件夹
    required=True,
    widget=None,
    label=None,
    initial=None,
    help_text=''
 
GenericIPAddressField
    protocol='both',           both,ipv4,ipv6支持的IP格式
    unpack_ipv4=False          解析ipv4地址,如果是::ffff:192.0.2.1时候,可解析为192.0.2.1, PS:protocol必须为both才能启用
 
SlugField(CharField)           数字,字母,下划线,减号(连字符)
    ...
 
UUIDField(CharField)           uuid类型
    ...

【七】forms组件源码分析

"""
看源码可以提升编程能力(CBV源码)
也可以从中获取出更多的使用方式(JsonResponse)
"""
def is_valid(self):
    return self.is_bound and not self.errors
# 查看类源码发现只要给类传参self.is_bound肯定是True

@property
def errors(self):
   	if self._errors is None:
       self.full_clean()
    return self._errors
# 查看了源码发现self._errors初始化就是None 所以肯定走full_clean方法

# 查看源码发现校验数据的整个过程内部都有异常处理机制
from django.core.exceptions import ValidationError
raise ValidationError('用户名不存在 你个DSB')

【八】ModelForm简介

forms组件主要配合models里面的默写类一起使用 但是默写类里面的字段需要在forms类中相当于重写一遍 代码冗余
为了更好的结合forms与models的关系 有了一个ModelForm(基于forms组件)

class MyUser(forms.ModelForm):
    class Meta:
        model = models.User  # 指定关联的表
        fields = '__all__'  # 所有的字段全部生成对应的forms字段
        labels = {
            'name': '用户名',
            'age': '年龄',
            'addr': '地址',
            'email': '邮箱'
        }
        widgets = {
            "name": forms.widgets.TextInput(attrs={"class": "form-control"}),
        }


def reg(request):
    form_obj = MyUser()
    if request.method == 'POST':
        form_obj = MyUser(request.POST)
        if form_obj.is_valid():
            # form_obj.save()  # 新增数据
            edit_obj = models.User.objects.filter(pk=5).first()
            form_obj = MyUser(request.POST, instance=edit_obj)  # 是新增还是保存就取决于有没有instance参数
            form_obj.save()  # 编辑数据
    return render(request, 'reg.html', locals())

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值