Confusion when importing Django' generic class based views

Viewed 152

While exploring the reference documentation and some tutorials I have seen the import for Django's generic class based views used in multiple ways:

from django.views.generic import TemplateView, ListView

Or:

from django.views.generic.base import TemplateView
from django.views.generic.list import ListView

I have tried experimenting with both tactis and they both seem to work, yet the first option seems less correct.

Do all the generic CBVs also exist within the generic module a well as the submodules? Can Python import classes from submodules by only importing a higher module? What is actually happening here?

Any help would be greatly appreciated!

2 Answers

Django like Python says that you need to be explicit and specific, you will find in the official documentation that the way Django import all generic views are as follow :

from django.views.generic import CreateView 

When reading this line you understand that you are import generics view and only one in particular.

From the documentation regarding imports :

Whenever possible, be as explicit as possible with imports.

I would say all are fine except the last one, this bad pratice regarding the PEP8

After some digging it seems that within django.views.generic.__init__.py all the other generic CBVs are imported allowing intentional access to them within django.views.generic. This seems to be the standardised way of importing the generic CBVs.

Related