在 Django 中设置分页时出现 Python 类型错误

标签 python django pagination

您好,我正在按照官方文档为我的网站设置分页,我的索引模板如下所示;

{% 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>

我的 View 是这样的;

# 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 是由于分页器没有输出任何值造成的?我的回溯不太有用,但在这里

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'

非常感谢任何关于可能出错的指导。

最佳答案

在你的第一个 catch 中添加 TypeError:

except (PageNotAnInteger, TypeError):
    # ...

但是如果你得到这样的页码,你也可以避免这个错误:

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

关于在 Django 中设置分页时出现 Python 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6789004/

相关文章:

python - 多个 PyQt5.QtWidgets.QApplication 对象的段错误

django - PicklingError : Can't pickle suds. sudsobject.User : attribute lookup suds. sudsobject.User 失败

c# - Linq 分页 - 如何解决性能问题?

python - 管理员中的 Django 模型验证

django - 关于 Django 的优秀视频讲座的任何建议

javascript - 为什么我的 JavaScript 分页代码显示当前页面之前的条目数?

python - Django 自定义分页 - 在 settings.py 中设置为默认值

python - valueError 格式中的零长度字段名称

基于 Python 的网络报告工具?

python - 如何将 python 脚本中的字典 POST 到 django url?