gpt4 book ai didi

python - 模板的 Django 上下文变量名称

转载 作者:行者123 更新时间:2023-12-01 03:41:14 26 4
gpt4 key购买 nike

编辑:我知道我可以更改变量的名称。我的问题是我不想这样做。我想知道django自动生成的所有变量是什么。

<小时/>

我正在做 Django 的入门教程,我正在 generic views section它在某一时刻解释道:

In previous parts of the tutorial, the templates have been provided with a context that contains the question and latest_question_list context variables. For DetailView the question variable is provided automatically – since we’re using a Django model (Question), Django is able to determine an appropriate name for the context variable. However, for ListView, the automatically generated context variable is question_list.

我的问题是我不知道 Django 如何确定这个“适当的名称”。当我编写自己的模板时我想知道这一点。我想知道在这样的模板中使用什么上下文变量名称。

据我所知,如果我的模型是 Question,则 question 上下文变量将存储该问题,而 question_list 上下文变量将存储该问题将存储每个问题。

所以我的疑问是:我还可以使用哪些其他上下文变量名称?他们会储存什么?我似乎在文档中找不到此内容,如果您知道它在哪里,请将我重定向到它。

最佳答案

您可以使用 context_object_name 将 Question_list 更改为其他内容这在文档的那一部分中没有得到很好的解释,但是......

Return the context variable name that will be used to contain the list of data that this view is manipulating. If object_list is a queryset of Django objects and context_object_name is not set, the context name will be the model_name of the model that the queryset is composed from, with postfix '_list' appended. For example, the model Article would have a context object named article_list.

get_context_object_name 下给出方法

这就是该方法的 code看起来,它应该消除所有疑虑:

    """
Get the name of the item to be used in the context.
"""
if self.context_object_name:
return self.context_object_name
elif hasattr(object_list, 'model'):
return '%s_list' % object_list.model._meta.model_name
else:
return None

关于python - 模板的 Django 上下文变量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39611973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com