s14_10_分页 组合搜索

- 分页(自定义的分页)
        
    - html
        {{ page_str|safe }}
        
    - views    
        
        from django.utils.safestring import mark_safe
        mark_safe(page_str)
        
    - 分页示例    
    

- 分页示例

    # utils\pagination.py

        from django.utils.safestring import mark_safe

        class Page:
            def __init__(self, current_page, data_count, per_page_count=10, pager_num=9):
                self.current_page = current_page
                self.data_count = data_count
                self.per_page_count = per_page_count
                self.pager_num = pager_num

            @property
            def start(self):
                return (self.current_page - 1) * self.per_page_count

            @property
            def end(self):
                return self.current_page * self.per_page_count

            @property
            def total_count(self):
                v, y = divmod(self.data_count, self.per_page_count)
                if y:
                    v += 1
                return v

            def page_str(self, base_url):
                page_list = []
                flag_fir = 0
                flag_end = 1

                if self.total_count < self.pager_num:
                    flag_end = 0
                    start_index = 1
                    end_index = self.total_count + 1

                else:
                    if self.current_page <= (self.pager_num + 1) / 2:
                        start_index = 1
                        end_index = self.pager_num + 1
                    else:
                        flag_fir = 1
                        start_index = self.current_page - (self.pager_num - 1) / 2
                        end_index = self.current_page + (self.pager_num + 1) / 2
                        if (self.current_page + (self.pager_num - 1) / 2) >=  self.total_count:
                            flag_end = 0
                            end_index = self.total_count + 1
                            start_index = self.total_count - self.pager_num + 1

                fir = '<a class="page" href="%s?p=%s">%s</a>' % (base_url,1,1)
                if flag_fir:
                    page_list.append(fir)

                if self.current_page == 1:
                    prev = '<a class="page" href="javascript:void(0);">上一页</a>'
                else:
                    prev = '<a class="page" href="%s?p=%s">上一页</a>' % (base_url, self.current_page - 1,)
                page_list.append(prev)

                for i in range(int(start_index), int(end_index)):
                    if i == self.current_page:
                        temp = '<a class="page active" href="%s?p=%s">%s</a>' % (base_url, i, i)
                    else:
                        temp = '<a class="page" href="%s?p=%s">%s</a>' % (base_url, i, i)
                    page_list.append(temp)

                if self.current_page == self.total_count:
                    nex = '<a class="page" href="javascript:void(0);">下一页</a>'
                else:
                    nex = '<a class="page" href="%s?p=%s">下一页</a>' % (base_url, self.current_page + 1,)
                page_list.append(nex)

                end = '<a class="page" href="%s?p=%s">%s</a>' % (base_url,self.total_count,self.total_count)
                if flag_end:
                    page_list.append(end)

                jump = """
                <input style="width:50px;height:20px;" type='text'/><a onclick='jumpTo(this, "%s?p=");'> GO</a>
                <script>
                    function jumpTo(ths,base){
                        var val = ths.previousSibling.value;
                            if( /^\d+$/.test(val) && val < %s ){
                                location.href = base + val;
                            }
                    }
                </script>
                """ % (base_url,self.total_count,)

                page_list.append(jump)
                page_str = mark_safe("".join(page_list))
                return page_str
        
    
    # html(含基于cookies的跳转,插件:jquery-1.12.4.js jquery.cookie.js)

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                .pagination .page{
                    display: inline-block;
                    padding: 5px;
                    
                    margin: 5px;
                }
                .pagination .page.active{
                    background-color: cornflowerblue;
                    color: white;
                }
            </style>
        </head>
        <body>
            <ul>
                {% for item in li %}
                    <li>{{ item }}</li>
                {% endfor %}
            </ul>

            <div>
                <select id="ps" onchange="changePageSize(this)">
                    <option value="10">10</option>
                    <option value="30">30</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                </select>
            </div>

            <div class="pagination">
                {{ page_str }}
            </div>


            <script src="/static/jquery-1.12.4.js"></script>
            <script src="/static/jquery.cookie.js"></script>
            <script>

                $(function(){
                        var v = $.cookie('per_page_count');
                        $('#ps').val(v);
                });
                function changePageSize(ths){
                    var v = $(ths).val();
                    console.log(v);
                    $.cookie('per_page_count',v, {'path': "/user_list/"});
                    location.reload();
                }
            </script>
        </body>
        </html>

    # urls.py
    
         url(r'^user_list/', views.user_list),
        
    # views.py

        from  utils import pagination
        LIST = []
        for i in range(499):
            LIST.append(i)

        def user_list(request):
            current_page = request.GET.get('p', 1)
            current_page = int(current_page)

            val = request.COOKIES.get('per_page_count',10)
            val = int(val)
            
            page_obj = pagination.Page(current_page,len(LIST),val)
            data = LIST[page_obj.start:page_obj.end]
            page_str = page_obj.page_str("/user_list/")
            return render(request, 'user_list.html', {'li': data,'page_str': page_str})
            
- 组合搜索

    # model.py
        from django.db import models

        # Create your models here.
        class Category(models.Model):
            caption = models.CharField(max_length=16)

        class ArticleType(models.Model):
            caption = models.CharField(max_length=16)

        class Article(models.Model):
            title = models.CharField(max_length=32)
            content = models.CharField(max_length=255)

            category = models.ForeignKey(Category)
            article_type = models.ForeignKey(ArticleType)

            # type_choice=(
            #     (1,'Python'),
            #     (2,'Openstack'),
            #     (3,'Linux'),
            # )
            # article_type = models.IntegerField(choices=type_choice)
            # 内存级别分类
    # url.py
    
        from app01 import views
        urlpatterns = [
            url(r'^admin/', admin.site.urls),
            url(r'^article-(?P<article_type_id>\d+)-(?P<category_id>\d+).html', views.article,name='article'),
        ]
    # views.py
    
        from django.shortcuts import render
        from app01 import models
        # Create your views here.
        def article(request,*args,**kwargs):
            # print(request.path_info)
            # from django.urls import reverse
            # url = reverse('article',kwargs={'article_type_id': '1', 'category_id': '1'})
            # print(url)
            print(kwargs)
            # {'article_type_id': '1', 'category_id': '1'}
            # url 中字段设置需与数据库中参数一致,方可如此传递**kwargs
            condition ={}
            for k,v in kwargs.items():
                kwargs[k] = int(v)
                if v == '0':
                    pass
                else:
                    condition[k] = v

            article_type_list= models.ArticleType.objects.all()

            # article_type_list = models.Article.type_choice
            # 内存级别分类时

            category_list= models.Category.objects.all()
            # c = {'article_type_id': '1', 'category_id': '1'}
            result = models.Article.objects.filter(**condition)

            return render(
                request,
                'article.html',
                {
                    'result':result,
                    'article_type_list':article_type_list,
                    'category_list':category_list,
                    'arg_dict':kwargs
                })

    # article.html(含simple_tag)

        {% load filter %}
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                .condition a{
                   display: inline-block;
                    padding: 3px 5px;
                    border: 1px solid #DDDDDD;
                    margin: 5px;
                }
                .condition a.active{
                    background-color: deepskyblue;
            </style>

        </head>
        <body>
            <h1>过滤条件</h1>
            <div class="condition">
                <div>
                    {% filter_all arg_dict 'article_type_id' %}
                    <!--
                    {% if arg_dict.article_type_id == 0 %}
                        <a class="active" href="/article-0-{{ arg_dict.category_id }}.html" >全部</a>
                    {% else %}
                        <a href="/article-0-{{ arg_dict.category_id }}.html" >全部</a>
                    {% endif %}
                    -->

                    {% filter_article_type article_type_list arg_dict %}
                    <!--
                    {% for row in article_type_list %}
                        {% if row.id == arg_dict.article_type_id %}
                            <a class="active" href="/article-{{ row.id }}-{{ arg_dict.category_id }}.html">{{ row.caption }}</a>
                        {% else %}
                            <a href="/article-{{ row.id }}-{{ arg_dict.category_id }}.html">{{ row.caption }}</a>
                        {% endif %}
                    {% endfor %}
                    -->
                </div>

                <div>
                    {% filter_all arg_dict 'category_id' %}
                    <!--
                    {% if arg_dict.category_id == 0 %}
                        <a class="active" href="/article-{{ arg_dict.article_type_id }}-0.html" >全部</a>
                    {% else %}
                        <a href="/article-{{ arg_dict.article_type_id }}-0.html" >全部</a>
                    {% endif %}
                    -->

                    {% for row in category_list %}
                        {% if row.id == arg_dict.category_id %}
                            <a class="active" href="/article-{{ arg_dict.article_type_id }}-{{ row.id }}.html" >{{ row.caption }}</a>
                        {% else %}
                            <a href="/article-{{ arg_dict.article_type_id }}-{{ row.id }}.html" >{{ row.caption }}</a>
                        {% endif %}
                    {% endfor %}
                </div>
            </div>
            <h1>查询结果</h1>
            <ul>
                {% for row in result %}
                    <li>{{ row.id }} - {{ row.title }}</li>
                {% endfor %}
            </ul>
        </body>
        </html>    
        
    # app01/templatetags/filter.py
    
        from django import template
        from django.utils.safestring import mark_safe
        register = template.Library()

        @register.simple_tag
        def filter_all(arg_dict,k):
            """
            {% if arg_dict.article_type_id == 0 %}
                <a class="active" href="/article-0-{{ arg_dict.category_id }}.html" >全部</a>
            {% else %}
                <a href="/article-0-{{ arg_dict.category_id }}.html" >全部</a>
            {% endif %}
            :param arg_dict:
            :return:
            """
            if k == 'article_type_id' :
                n1 = arg_dict['article_type_id']
                n2 = arg_dict['category_id']
                if n1 == 0:
                    ret='<a class="active" href="/article-0-%s.html" >全部</a>' % n2
                else:
                    ret='<a  href="/article-0-%s.html" >全部</a>' % n2
            else:
                 n1 = arg_dict['category_id']
                 n2 = arg_dict['article_type_id']
                 if n1 == 0:
                     ret='<a class="active" href="/article-%s-0.html" >全部</a>' % n2
                 else:
                     ret='<a  href="article-%s-0.html" >全部</a>' % n2
            return mark_safe(ret)

        @register.simple_tag
        def filter_article_type(article_type_list,arg_dict):
            """
            {% for row in article_type_list %}
                {% if row.id == arg_dict.article_type_id %}
                    <a class="active" href="/article-{{ row.id }}-{{ arg_dict.category_id }}.html">{{ row.caption }}</a>
                {% else %}
                    <a href="/article-{{ row.id }}-{{ arg_dict.category_id }}.html">{{ row.caption }}</a>
                {% endif %}
            {% endfor %}
            :return:
            """
            ret =[]
            for row in article_type_list:
                if row.id == arg_dict['article_type_id']:
                    temp = '<a class="active" href="/article-%s-%s.html">%s</a>' %(row.id,arg_dict['category_id'],row.caption)
                else:
                    temp = '<a href="/article-%s-%s.html">%s</a>' %(row.id,arg_dict['category_id'],row.caption)
                ret.append(temp)

                """
                if row[0] == arg_dict['article_type_id']:
                    temp = '<a class="active" href="/article-%s-%s.html">%s</a>' %(row[0],arg_dict['category_id'],row[1])
                else:
                    temp = '<a href="/article-%s-%s.html">%s</a>' %(row[0],arg_dict['category_id'],row[1])
                ret.append(temp)
                # 内存级别分类
                """

            return mark_safe(''.join(ret))

posted @ 2020-01-18 21:40  badweather  阅读(96)  评论(0编辑  收藏  举报