Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于类的视图如何确定将调用哪个模板文件?_Python_Django - Fatal编程技术网

Python 基于类的视图如何确定将调用哪个模板文件?

Python 基于类的视图如何确定将调用哪个模板文件?,python,django,Python,Django,代码如下: # urls.py urlpatterns = [ path("books/", views.BookListView.as_view(), name="books"), ] 以及意见 # views.py class BookListView(generic.ListView): model = Book Book是models.py中的一个类,此视图将使用Book\u list.html模板。我的问题是: 为什么它知道将调用什么模板?我甚至没有给它起模板名

代码如下:

# urls.py

urlpatterns = [
    path("books/", views.BookListView.as_view(), name="books"),
]
以及意见

# views.py

class BookListView(generic.ListView):
    model = Book
Bookmodels.py中的一个类,此视图将使用Book\u list.html模板。我的问题是:

为什么它知道将调用什么模板?我甚至没有给它起模板名。就这样

template_name = 'book_list.html'

列表视图中当您没有明确指定
模板名称
时,它将使用小写的模型名称,并在末尾添加_列表。就像你的模型是书一样,它会搜索
Book\u list.html

如果希望应用自己的后缀而不是
\u list
,则需要如下指定:

template\u name\u suffix='\u myown
'


此外,查看基于类的视图的所有方法和用法非常有用。

它将查找
book\u list.html
,因为该类的默认
模板\u name\u后缀
属性定义为
\u list
,这意味着,如果您没有自己定义
模板名
模板名
后缀,Django将查找
图书列表.html
模板

book
部分来自这样一个事实,即您的模型名为
book
,然后它与
模板\u名称\u后缀
连接,在本例中与
\u列表
连接,最后,
.html
作为文件扩展名附加


您可以查看实际代码。(
ListView
继承自
MultipleObjectTemplateResponseMixin

通用ListView将查找带有“\u list”的型号名称和后缀。看看下面用Django做这个的类

class MultipleObjectTemplateResponseMixin(TemplateResponseMixin):
    """
    Mixin for responding with a template and list of objects.
    """
    template_name_suffix = '_list'

    def get_template_names(self):
        """
        Return a list of template names to be used for the request. Must return
        a list. May not be called if render_to_response is overridden.
        """
        try:
            names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
        except ImproperlyConfigured:
            # If template_name isn't specified, it's not a problem --
            # we just start with an empty list.
            names = []

        # If the list is a queryset, we'll invent a template name based on the
        # app and model name. This name gets put at the end of the template
        # name list so that user-supplied names override the automatically-
        # generated ones.
        if hasattr(self.object_list, 'model'):
            opts = self.object_list.model._meta
            names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))

        return names