“page”GET参数来自哪里?

时间:2018-03-30 19:06:38

标签: django django-models

我是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,当我启动应用程序时,如果我传递密钥“page”,为什么它会起作用?

我的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>

1 个答案:

答案 0 :(得分:3)

如果请求中没有参数(当您直接点击http://localhost:8000时),page的值将为None。这是request.GET.get()的默认行为,因为它无法找到您要求的密钥 - 与普通的Python字典相同(因为GET扩展了它)。

# page will be None
page = request.GET.get("page")

这意味着None会传递给paginator.page()

try:
    # Passing None here
    posts = paginator.page(page)
except PageNotAnInteger:

这可能意味着(虽然我们无法看到paginagor的代码)引发PageNotAnInteger异常,因此将值1传递给paginagor.page()

try:
    posts = paginator.page(page)  # Raises PageNotAnInteger because None passed
except PageNotAnInteger:
    # Posts are retrieved for page 1
    posts = paginator.page(1)

上述调用中的posts以及page(仍为None)的值随后会传递给模板。

return render(request, "post/list.html", {"page": page, "posts": posts});

模板list.html然后迭代帖子并显示它们。

相当令人困惑的是,当包含pagination.html模板时,它将一个名为page的上下文变量定义为当前值posts

<!-- Pass the value of posts using a variable name of page -->
{% include "pagination.html" with page=posts %}

因此,pagination.html模板引用page的地方实际上使用的是posts的值。

<!-- Really posts.number and posts.paginator.num_pages -->
Page {{ page.number }} of {{ page.paginator.num_pages }}

希望有助于解释事情。

另外一件事,你不需要在Python的每一行的末尾添加一个分号。