我是 Django 的新手。现在我正在学习使用基于类的通用视图。有人可以解释一下context_object_name属性的目的和用途吗?
4 回答
如果您不提供“context_object_name”,您的视图可能如下所示:
<ul>
{% for publisher in object_list %}
<li>{{ publisher.name }}</li>
{% endfor %}
</ul>
但是如果你提供像 {"context_object_name": "publisher_list"},那么你可以编写如下视图:
<ul>
{% for publisher in publisher_list %}
<li>{{ publisher.name }}</li>
{% endfor %}
</ul>
这意味着您可以通过“context_object_name”为您的视图将原始参数名称(object_list)更改为任何名称。希望有所帮助:)
好的,我自己搞定了!:)
它只是从模板访问的易于理解的变量名称
让我们假设以下帖子/views.py:
# posts/views.py
from django.views.generic import ListView from .models import Post
class HomePageView(ListView):
model = Post
template_name = 'home.html'
在第一行,我们导入 ListView,在第二行,我们需要明确定义我们正在使用的模型。在视图中,我们继承 ListView,指定我们的模型名称并指定我们的模板引用。ListView 在内部返回一个我们希望在模板中显示的名为object_list的对象。
在我们的模板文件 home.html 中,我们可以使用 Django 模板语言的 for 循环来列出object_list中的所有对象
为什么是 object_list?这是 ListView 返回给我们的变量的名称。
让我们看看我们的模板/home.html
<!-- templates/home.html -->
<h1>Message board homepage</h1>
<ul>
{% for post in object_list %}
<li>{{ post }}</li>
{% endfor %}
</ul>
你看到上面的 object_list 了吗?这不是一个非常友好的名字吗?为了使其更加用户友好,我们可以使用 context_object_name提供一个明确的名称。
这有助于任何其他阅读代码的人理解模板上下文中的变量,而且它更容易阅读和理解。
所以让我们回到我们的 posts/views.py 并通过添加以下一行来更改它:
context_object_name = 'all_posts_list' # <----- new
所以我们的新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
我们不要忘记现在更新我们的模板:
<!-- templates/home.html -->
<h1>Message board homepage</h1>
<ul>
{% for post in all_posts_list %}
<li>{{ post }}</li>
{% endfor %}
</ul>
你可以作为 object_list 离开,它仍然可以工作,但你明白了。
考虑这两个代码片段
A. 使用基于函数的视图:
def index(request):
product_list = Product.objects.all()
return render(request, 'product/index.html', {'product_list': **product_list**})
B. 使用基于类的视图
class ProductListView(ListView):
model = Product
template_name = 'product/index.html'
context_object_name = 'product_list'
在上述两种方法中,您的上下文变量将是“product_list”,而您的 HTML 将是,
{% for product in product_list %}
<div class="row">
<div class="col-md-3 offset-md-2">
<img src="{{product.product_image}}" class="card" height="150px" />
</div>
<div class="col-md-4">
<h3>{{product.product_name}}</h3>
.......
</div>
<div class="col-md-2">
.........
</div>
</div>
{% endfor %}