Django Tips #2: Imports
Imports are an inevitable part of Python and Django development. Pep8 which is the official style guide for Python, recommends imports be placed at the top of the file, on separate lines, and grouped in the following order:
- Standard library imports
- Related third party imports
- Local application/library specific imports
Whenever possible, be as explicit as possible with imports.
Here’s an example
views.py file from the Blog app built in my Django for Beginners book.
# blog/views.py from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Post # explicit relative import class BlogListView(ListView): model = Post template_name = 'home.html'
The top 3 lines are absolute imports which are used when importing packages from outside a given app. This is how all Django core code is imported.
The database model is imported using an explicit relative import–we didn’t hardcode the app name in here which makes it much more reusable. If we had instead done
from blog.models import Post then if the name of the
blog app changed in the future or we wanted to separate out this code, the import would fail.
Another good rule of thumb is to never use
* which accesses all imports. For example, this is a bad idea:
# blog/views.py from django.views.generic import * # BAD IDEA!
Why import things you don’t need? Plus what if
views.generic changes at some point in the future in unforeseen ways which opens up security concerns.
You’ll likely see different import styles in open source and professional code settings. Try to follow PEP8 as closely as possible. Use absolute imports when necessary and prefer explicit relative imports for your local Django code.