分页器与form表单

分页器

分页器对象

from django.core.paginator import Paginator
Paginator对象:    paginator = Paginator(user_list, 10)
per_page: 每页显示条目数量
count:    数据总个数
num_pages:总页数
page_range:总页数的索引范围,如: (1,10),(1,200)
page:     page对象   

page对象

page对象:page=paginator.page(页码)  生成page对象,传页码,会生成对应页码数据
has_next              是否有下一页
next_page_number      下一页页码
has_previous          是否有上一页
previous_page_number  上一页页码
object_list           分页之后的数据列表
number                当前页
paginator             paginator对象

views中

def page_text(request):
    book_list = Books.objects.all()
    paginator = Paginator(book_list, 5)
    try:
        current_page = int(request.GET.get('page', 1))
        page = paginator.page(current_page)
    except Exception:
        current_page = 1
        page = paginator.page(current_page)
    if paginator.num_pages < 12:
        page_list = paginator.page_range
    else:
        if current_page < 6:
            page_list = range(1, 12)
        elif current_page > paginator.num_pages - 5:
            page_list = range(paginator.num_pages - 10, paginator.num_pages + 1)
        else:
            page_list = range(current_page - 5, current_page + 6)
    return render(request, 'page_text.html',locals())

html中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/page_text.css">
    <title>page_text</title>
</head>
<body>
<div class="container">
    <ul class="page_info">
        {% for book in page %}
            <li><span>书名:{{ book.name }}</span> <span>信息:{{ book.info }}</span></li>
        {% endfor %}
    </ul>


    <nav aria-label="Page navigation">
        <ul class="pagination">
            <li>

                {% if page.has_previous %}
                    <a href="?page={{ page.previous_page_number }}" aria-label="Previous">
                    <span aria-hidden="true">上一页</span>
                {% else %}
                    <span aria-hidden="true">上一页</span>
                {% endif %}

                </a>
            </li>
            {% for page in page_list %}
                {% if current_page == page %}
                    <li class="active"><a href="/page_text/?page={{ page }}">{{ page }}</a></li>
                {% else %}
                    <li><a href="/page_text/?page={{ page }}">{{ page }}</a></li>
                {% endif %}

            {% endfor %}
            <li>
                {% if page.has_next %}
                    <a href="?page={{ page.next_page_number }}" aria-label="Previous"></a>
                    <span aria-hidden="true">下一页</span>
                {% else %}
                    <span aria-hidden="true">下一页</span>
                {% endif %}
            </li>
        </ul>
    </nav>
</div>

</body>
</html>

form组件

模板层

class UserInfo(models.Model):
    name=models.CharField(max_length=32)
    pwd=models.CharField(max_length=32)
    email=models.EmailField(

views层

from django import forms
from django.forms import widgets

from django.core.exceptions import ValidationError


class RegForm(forms.Form):
    name = forms.CharField(required=True, max_length=10, min_length=1, label='用户名', error_messages=
    {'required': '该字段必填', 'max_length': '太长了', 'min_length': '太短了'},
                           widget=widgets.TextInput(attrs={'class': 'form-control error'}))
    pwd = forms.CharField(required=True, max_length=10, min_length=1, label='密码', error_messages=
    {'required': '该字段必填', 'max_length': '太长了', 'min_length': '太短了'},
                          widget=widgets.PasswordInput(attrs={'class': 'form-control error'}))
    re_pwd = forms.CharField(required=True, max_length=10, min_length=1, label='确认密码', error_messages=
    {'required': '该字段必填', 'max_length': '太长了', 'min_length': '太短了'},
                             widget=widgets.PasswordInput(attrs={'class': 'form-control error'}))
    email = forms.EmailField(required=True, label='邮箱', error_messages=
    {'required': '该字段必填', 'invalid': '不符合邮箱格式'},
                             widget=widgets.PasswordInput(attrs={'class': 'form-control error'}))
                             
    def clean_name(self):   # 局部钩子(多了一个我自己写校验规则的方式)
        name = self.cleaned_data.get('name')
        user = UserInfo.objects.filter(name=name).first()
        if user:
            raise ValidationError('用户已经存在')
        else:
            if name.startswith('sb'):
                raise ValidationError('不能以sb开头')
            return name

    def clean(self):        # 全局钩子
        pwd = self.cleaned_data.get('pwd')
        re_pwd = self.cleaned_data.get('re_pwd')
        if pwd and re_pwd:
            if pwd == re_pwd:
                return self.cleaned_data
            else:
                raise ValidationError('两次密码不一致')


def form_test(request):
    form_obj = RegForm()
    # from类里没有的字段,不会做校验,而且,一旦校验通过,cleaned_data 里面也没有这个字段
    if request.method == 'POST':
        form_obj = RegForm(request.POST)
        if form_obj.is_valid(): # is_valid 返回一个布尔类型,true代表,里面所有字段,都校验通过
            UserInfo.objects.create(**form_obj.cleaned_data)    # cleaned_data 校验通过的字段,放在里面
            # return HttpResponse('ok')

        else:
            print(form_obj.errors.as_data())
            errors = form_obj.errors.get('__all__', '')
            # print(form_obj['name'].errors)
            # return HttpResponse('失败')

    return render(request, 'forms_test.html', locals())

html中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <title>Title</title>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">

            <form action="" method="post">
                <p>用户名:<input type="text" name="name" class="form-control" aa="ddd"></p>
                <p>密码:<input type="password" name="pwd" class="form-control"></p>
                <p>确认密码:<input type="password" name="re_pwd" class="form-control"></p>
                <p>邮箱<input type="text" name="email" class="form-control"></p>
                <input type="submit">
            </form>

            <h3>方法一</h3>

            <form action="" method="post" novalidate>   # novalidate代表不使用前端验证
                <p>{{ form_obj.name.label }}:{{ form_obj.name }} <span
                        class="danger">{{ form_obj.name.errors.0 }}</span></p>
                <p>{{ form_obj.pwd.label }}:{{ form_obj.pwd }} <span class="danger">{{ form_obj.pwd.errors.0 }}</span>
                </p>
                <p>{{ form_obj.re_pwd.label }}:{{ form_obj.re_pwd }} <span
                        class="danger">{{ form_obj.re_pwd.errors.0 }}{{ errors }}</span></p>
                <p>{{ form_obj.email.label }}:{{ form_obj.email }} <span
                        class="danger">{{ form_obj.email.errors.0 }}</span></p>
                <input type="submit">
            </form>

            <h3>方法二</h3>

            <form action="" method="post" novalidate>
                {% for foo in form_obj %}
                    <p>{{ foo.label }}:{{ foo }}<span class="danger">{{ foo.errors.0 }}</span></p>
                {% endfor %}
                {{ errors }}
                <input type="submit">
            </form>

            <h3>方法三</h3>
            <form action="" method="post" novalidate>
                {{ form_obj.as_p }}
                <input type="submit">
            </form>
        </div>
    </div>
</div>

</body>
</html>
posted @ 2018-09-16 16:20  luck_L  阅读(1482)  评论(0编辑  收藏  举报