您好我正在关注官方文档并为我的网站设置分页,我的索引模板看起来像这样;
{% for post in list_of_posts %}
<div class="body"><a class="title" href="/post/{{post.id}}"><h2>{{ post.title }}</h2></a>
<P>{{ post.body|truncatewords:50|wordwrap:110 }}</P>
<h3>{{ post.date|date:"jS F Y" }}</h3>
<hr>
</div>
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if post.has_previous %}
<a href="?page={{ post.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ post.number }} of {{ contacts.paginator.num_pages }}.
</span>
{% if post.has_next %}
<a href="?page={{ post.next_page_number }}">next</a>
{% endif %}
</span>
</div>
我的观点看起来像这样;
# Main page
def index(request):
list_of_posts = Post.objects.all().order_by('-date')
list_of_posts = list_of_posts.filter(published=True)
paginator = Paginator(list_of_posts, 10)
page = request.GET.get('page')
try:
post = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
post = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
post = paginator.page(paginator.num_pages)
return render_to_response('index.html', {'list_of_posts': list_of_posts})
我觉得TypeError是因为paginator没有输出任何值?我的回溯不是很有帮助,但这里是
Exception Value:
int() argument must be a string or a number, not 'NoneType'
Exception Location: C:\Python27\lib\site-packages\django\core\paginator.py in validate_number, line 23
TypeError at /
int() argument must be a string or a number, not 'NoneType'
非常感谢任何可能出现问题的指导。
答案 0 :(得分:4)
在第一个catch中添加TypeError:
except (PageNotAnInteger, TypeError):
# ...
但如果你得到这样的页码,你也可以避免这个错误:
page = request.GET.get("page", 1)
答案 1 :(得分:0)
视图函数的主体没有缩进。这就是它在这个页面上的表现吗?
此外,它不应该避免错误,但看起来你没有将post变量发送到模板(而不是list_of_posts)。
最后,您是否在模块的顶部有这个...
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
答案 2 :(得分:0)
我在这里为pagination
添加一个小代码希望它会帮助你:
def pagination(request, list_of_posts, result_per_page):
paginator = Paginator(list_of_posts, result_per_page)
try: // **Most probably here your code is doing somthing wrong**.
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
posts = paginator.page(page)
except (EmptyPage, InvalidPage):
posts = paginator.page(paginator.num_pages)
return posts