【发布时间】:2018-09-09 19:47:34
【问题描述】:
我是 Django 的初学者,对于 Django 引擎盖下的实际工作方式,我深思熟虑。我目前正在我的网络应用中实现分页。
看看这个 view.py 文件:
def post_list(request):
object_list = Post.published.all(); # '.published' is a manager.
paginator = Paginator(object_list, 3); # 3 posts in each page.
page = request.GET.get("page");
try:
posts = paginator.page(page);
except PageNotAnInteger:
posts = paginator.page(1);
except EmptyPage:
posts = paginator.page(paginator.num_pages);
return render(request, "post/list.html", {"page": page, "posts": posts});
request.GET 不是一个字典对象,包含了 url 中所有的 GET 请求参数,以及用于返回值的 .get() 方法 对于参数内的给定键?当我启动应用程序时,由于我的 URL 目前只是 localhost:8000,为什么如果我传递密钥“页面”它会起作用?
我的 list.html 文件:
{% extends "base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
<h1>My Blog</h1>
{% for post in posts %}
<h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2> <!-- How does this absurl work?-->
<p class="date">Published {{ post.publish }} by {{ post.author }}</p> <!-- What does '.publish' print?-->
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% include "pagination.html" with page=posts %}
<!-- The statement above is the little menu: "Page 1 of 2. Next" -->
<!-- It also sends the 'page' variable as a GET parameter. -->
{% endblock %}
我的 pagination.html 文件:
<!-- This pagination template expects a paginator object. -->
<div class="pagination">
<span class="step-links">
{% if page.has_previous %}
<a href="?page={{ page.previous_page_number }}">Previous</a>
{% endif %}
<span class="current">
Page {{ page.number }} of {{ page.paginator.num_pages }}. <!-- what!? -->
</span>
{% if page.has_next %}
<a href="?page={{ page.next_page_number }}">Next</a>
{% endif %}
</span>
</div>
【问题讨论】:
-
这个问题对我来说没有意义。 “Django 怎么可能知道它不应该显示它应该显示的所有内容”这句话在逻辑上是不一致的。
-
已修复。非常感谢您的关注。
-
您正在捕获 PageNotAnInteger 异常,然后将 1 传递给 paginator.page 函数。然后你正在捕获一个 EmptyPage 异常,它看起来像正在使用默认/备用值。
-
为了更好地理解您的问题,您能否解释一下您到底对什么感到困惑?是不是不知道 Django 从哪里获取键值对来填充 request.GET 字典?
-
好的。我的问题是:如果“request.GET”是一个包含 GET 请求参数的字典,如果没有“page”参数,为什么我可以使用“page”作为“request.GET.get(“page”) 中的键在 GET 请求中?
标签: django django-models