模板的 Django 上下文变量名称

Django context variable names for the templates

编辑: 我知道我可以更改变量的名称。我的问题是我不想那样做。我想知道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 如何确定这个 "appropriate names"。我想在编写自己的模板时知道这一点。我想知道在这样的模板中使用什么上下文变量名称。

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

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

我认为这个默认的上下文变量名称仅适用于处理 Django 的 Class 基于视图的情况。

例如如果您正在为 Animal 模型使用 DetailView,Django 将自动创建一个名为 'animal' 的上下文变量供您在模板中使用。我认为它也允许使用 'object'。

正如您提到的,另一个示例是 Animal 模型的 ListView,它会生成名为 animal_list 的上下文名称。

但是,在这两种情况下,都可以通过多种方式更改默认的上下文变量名称。如果您在 DetailView 中指定 'context_object_name',这将是您在模板中引用的名称。这也适用于 ListViews。

这个网站有所有 Django 版本的 CBV 的所有信息:

https://ccbv.co.uk/projects/Django/1.9/django.views.generic.detail/DetailView/

您可以使用 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