1

我是 django 和 python 的新手,我有视图函数,它从数据库中检索一些数据并将它们显示在页面上。但是有一个问题,所有数据都显示在一个页面上但是我需要分开,它必须在每页上显示 6 个数据,如果数据数量超过 6 个,用户可以在下一页阅读它们。我不知道该怎么做

我的观点是:

   def search1(request):
        if request.method == 'POST':
            form = SearchForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                books=data(cd)
                return render_to_response('result.html', {'books': books, 'form': form})
        else:
            form = SearchForm()
        return render_to_response('form.html', {'form': form})

我的模板:

    {% if books %}
    <p>Found {{ books|length }} book{{ books|pluralize }}.</p>
    <ul dir=rtl>
        {% for book in books %}
        <p>title:  {{ book.title }}</p>
        <p>price:  {{ book.price }}</p>
        {% endfor %}
    </ul>
{% else %}
    <p>No books matched your search criteria.</p>
{% endif %}
4

2 回答 2

1

看看django 分页器

于 2012-11-07T06:52:04.957 回答
-1

我修改了使用分页器的代码,但是在结果页面中,当我单击下一步时,它再次显示我的搜索页面。问题是什么?看法:

def search1(request):
    if request.method == 'POST':
    form = SearchForm(request.POST)
        if form.is_valid():
        cd = form.cleaned_data
        book_list=data(cd)
        paginator = Paginator(book_list, 6)
        page = request.GET.get("page", 1)
        try:
            books = paginator.page(page)
        except (PageNotAnInteger, TypeError):
            # If page is not an integer, deliver first page.
            books = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            books = paginator.page(paginator.num_pages)

        return render_to_response('list.html', {"books": books})
else:
    form = SearchForm()
    return render_to_response('form.html', {'form': form})

模板 :

    {% for book in books.object_list %}
    {# Each "contact" is a Contact model object. #}
    {{ book.full_name|upper }}<br />
    {{book.froshande}}
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if books.has_previous %}
            <a href="?page={{ books.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ books.number }} of {{ books.paginator.num_pages }}.
        </span>

        {% if books.has_next %}
            <a href="?page={{ books.next_page_number }}">next</a>
        {% endif %}
    </span>
</div>
于 2012-11-07T08:57:11.280 回答