Django分页,翻阅,但现在显示数据

时间:2012-11-30 11:33:28

标签: python django pagination django-views django-pagination

会尽量保持简单! :)

我在我的django应用程序中设置了分页。我正在管理我在我的分页中设置的页面。每页有12页,每页10条新闻。我可以点击下一个和我希望查看的页码,哪一切都正常。

然而,来自后端的帖子中的数据没有显示,我看不出原因。我认为这是因为我没有从thr模板中正确访问模型。无论如何我的代码:

Views.py:

def press_list(request, template_name='pressbox/object_list.html', extra_context={}):
    category = PressCategory.objects.get()
    news_items = PressItem.objects.filter(is_active=True)

    paginator = Paginator(news_items, 10)

    page = request.GET.get('page', 1)

    this_page = paginator.page(page)


    page = int(page)

    try:
        this_page = paginator.page(page)
    except(EmptyPage, InvalidPage):
        raise Http404



    extra_context = {
        'category': category,
    'paginator': this_page.object_list,
    'paginator': paginator,
    "current_page_pag": page,
    'this_page': this_page,
    }
    return render_to_response(template_name, extra_context, RequestContext(request))

Pagination_template:

<div class="pag_wrap">
        <ul class='news_paginator'>
        <li class='prev'>{% if this_page.has_previous %}<a href='{{current_url}}?page={{this_page.previous_page_number}}'>&#60;</a>{% else %}<span>&#60;</span>{%endif%}</li>
        {% for page in paginator.page_range %}
        <li class='{% if forloop.last %}last {%endif%}{%ifequal current_page_pag page %}active {%endifequal%}'><a href='{{current_url}}?page={{page}}'>{{page}}</a></li>
        {% endfor %}
        <li class='next'>{% if this_page.has_next %}<a href='{{current_url}}?page={{this_page.next_page_number}}'>&#62;</a>{% else %}<span>&#62;</span>{%endif%}</li>
        </ul>
</div>

新闻发布内容:

 <ul class="article-list">
        {% for object in paginator.page_range %}
                <li class="{{ object.category.slug }}">
                <a href="{{ object.get_absolute_url }}">

                  <img class="news_thumbnail" src="/media/{{object.thumbnail}}" alt="thumbnail" />
              <strong class="article-title">{{ object.title }}</strong>
                  <span class="article-date">{{ object.published_on|date:"M d, Y" }}</span> 
                  {{ object.short_description }}
                 {% comment %} <span class="article-category">{{ object.category.slug }}</span> {% endcomment %}
                </a>
              </li>
    {% endfor %}
            </ul>

我确定这是 - {paforator.page_range%}中的对象行,它正在这样做,因为它只是循环遍历帖子数而不是内容。我不确定如何访问数据。

任何帮助都会非常感激。对Python和Django来说很陌生,我对迄今为止所做的事情印象深刻! :)

1 个答案:

答案 0 :(得分:4)

您在上下文中将this_page.object_listpaginator作为'paginator'传递。因此,paginator实际上不是模板中的oblect_list

但是您不需要在模板中传递它,而是可以使用this_page,因此您的模板可以更新为

<ul class="article-list">
    {% for object in this_page.object_list %}
       ... your rendering code ...
    {%endfor%}
</ul>

对于django 1.4及以上版本,您可以直接进行

{% for object in this_page %}
    ...
{%endfor%}

参考:Using Paginator in a view