Monday, June 27, 2016

Re: Please help me with CBV template_name behaviour.

As an afterthought, I wonder why my misspelling didn't cause an error instead of a "wrong" Template being used?

Any insights?


Not particularly. That should have caused an error. The only way it wouldn't have is if you have (or one of your installed apps has) a file named crudlist.htm inside of a folder named contacts. I'd be interested to see what the debug toolbar had to say while the typo was in place. 

As far as your question about template inheritance earlier, here is the link to the docs:


-James

I was unhappy with my own answer, so I did some digging. It looks like the typo worked accidentally "as designed".

A CBV (in this case inheriting from ListView) for model Foo, will return a default 'template_name' of 'foo_list.html'. What isn't necessarily obvious is that the value of 'template_name' is handled by the get_template_names() method:


The pluralized name of the method indicates that a list of template names are returned. If we look at the the code for MultipleObjectTemplateResponseMixin (which ListView inherits from at some point), we see what happens:


You'll see that a list is built that includes the value of 'template_name' (from TemplateResponseMixin) as well as the "generic" template name that is built using the app_label and model name (myapp/foo_list.html), so something like ['crudview.html', 'contact/contact_list.html'] in your case. 

Since the typo existed and you were using CBV's, Django simply moved on to the next available name in the list of templates, which happened to be added automatically as part of the CBV process, and happened to match the name of the template you were using as the baseline for your tests.

Hope that clears it up.

-James

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciUhEGUdN06ov6Y350oq7A3VO-8OEqgNdQPp-vOrZyS_%3Dw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment