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
Book是models.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