feldroy/django-crash-starter

Trying to understand 35 wiring in the list view url

bebekim opened this issue · 2 comments

Description

35 Wiring in the List View Url
Where in the everycheese/cheeses/urls.py does it state that the views.CheeseListView.as_view() will be wired to cheese_list.html?

Rationale

Just curiosity

Use case(s) / visualization(s)

For instance, I have changed cheese_list.html file name to cheese_array.html and path(..., name=array) and it won't work. I would like to know

I assume Django automatically looks for a template called <app_name>/<model>_list.html, which in this case would be cheeses/cheese_list.html. Here <model> is the model that is defined in CheesListView.

If you change the name of the url to 'array', then this template doesn't change, because it doesn't depend on the url name. In order to wire the view to cheese_array.html, you need to add template = 'cheeses/cheese_array in CheeseListView which will override the default.

@mathemaat

I assume Django automatically looks for a template called <app_name>/_list.html, which in this case would be cheeses/cheese_list.html. Here is the model that is defined in CheesListView.

If you change the name of the url to 'array', then this template doesn't change, because it doesn't depend on the url name. In order to wire the view to cheese_array.html, you need to add template = 'cheeses/cheese_array in CheeseListView which will override the default.

You are partially correct in your answer.

The most complete answer would be:

The main logic to define the name of the template is implemented in the get_template_names method of some views mixins classes.

The default implementation of the get_template_namesis defined on the TemplateResponseMixin class.

The mixin classe SingleObjectTemplateResponseMixin and MultipleObjectTemplateResponseMixin extends the TemplateResponseMixin implementation and overwrite it to add the concept of template_name_suffix and add the logic of a model instance instrospection to dynamic obtain the model name or app name + model name.

The CreateView, UpdateView and DeleteView simply compose with these mixin classes and modify template_name_suffix.

The inheritance and composition hierarchy of django views can be a little complex to understand. Something that always helps you find out where things are coming from is to manually explore function calls using the debugger of your choice and use https://ccbv.co.uk/ as additional documentation.