django视图中的context_object_name是什么?

meg*_*ido 21 django-class-based-views

我是django的新手.现在我正在学习使用基于类的通用视图.有人可以解释一下context_object_name属性的目的和用途吗?

use*_*922 47

如果您不提供"context_object_name",您的视图可能如下所示:

<ul>
    {% for publisher in object_list %}
        <li>{{ publisher.name }}</li>
    {% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)

但是,如果您提供类似{"context_object_name":"publisher_list"},那么您可以编写如下视图:

<ul>
    {% for publisher in publisher_list %}
        <li>{{ publisher.name }}</li>
    {% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)

这意味着您可以通过视图的"context_object_name"将原始参数名称(object_list)更改为任何名称.希望有帮助:)


meg*_*ido 19

好的,我自己搞定了!:)

从模板访问它只是一个人类可理解的变量名称

https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-display/#making-friendly-template-contexts

  • 这是最新版本的链接(版本1.8):https://docs.djangoproject.com/en/1.8/topics/class-based-views/generic-display/#making-friendly-template-contexts (2认同)

Str*_*ker 5

让我们假设以下posts / views.py:

# posts/views.py
from django.views.generic import ListView from .models import Post

class HomePageView(ListView): 
    model = Post
    template_name = 'home.html'
Run Code Online (Sandbox Code Playgroud)

在第一行中,我们要导入ListView,在第二行中,我们需要显式定义我们正在使用的模型。在视图中,我们子类化ListView,指定模型名称并指定模板引用。在内部,ListView返回一个要在模板中显示的对象object_list

在模板文件home.html中,我们可以使用Django模板语言的for循环列出object_list中的所有对象

为什么选择object_list?这是ListView返回给我们的变量的名称。

让我们看一下我们的template / home.html

<!-- templates/home.html -->
<h1>Message board homepage</h1> 
<ul>

     {% for post in object_list %} 

          <li>{{ post }}</li>

     {% endfor %} 
 </ul>
Run Code Online (Sandbox Code Playgroud)

您看到上面的object_list吗?这不是一个很友好的名字吗?为了使其更易于使用,我们可以改用context_object_name提供一个显式名称 。

这可以帮助其他阅读代码的人理解模板上下文中的变量,并且更易于阅读和理解。

因此,让我们回到我们的posts / views.py并通过添加以下一行来更改它:


context_object_name = 'all_posts_list' # <----- new
Run Code Online (Sandbox Code Playgroud)

因此,我们的新views.py现在看起来像这样:

# posts/views.py
from django.views.generic import ListView from .models import Post

class HomePageView(ListView): model = Post

    template_name = 'home.html'

    context_object_name = 'all_posts_list' # <----- new
Run Code Online (Sandbox Code Playgroud)

并且不要忘了立即更新模板:

<!-- templates/home.html -->
<h1>Message board homepage</h1> 
<ul>

   {% for post in all_posts_list %}

      <li>{{ post }}</li>

   {% endfor %} 

</ul>
Run Code Online (Sandbox Code Playgroud)

您本可以保留为object_list,但仍然可以使用,但是您明白了。