Imports in Django

Importing modules is an essential part of Python and Django development. PEP8 - the official style guide for Python, recommends place imports at the beginning of the file, on separate lines, and group them like this:

  1. Import standard libraries.
  2. Import third-party libraries.
  3. Import local applications or libraries.

Use this approach whenever possible to make it easier to work with imports.

Here is an example views.py for a blog application:

# 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 # relative import

class BlogListView(ListView):
     model = Post
     template_name = 'home.html'

The first three imports are absolute imports, which are used to import packages from the project's workbench or globally installed packages. This example shows the import of the main Django code.

We use a relative import to import our model, so we don't directly specify the application name, which makes the code more portable. If we used  from blog.models import Post, then if the name of the application (blog) later changes, we will have to edit the code wherever it is used.

Another great rule is to never import everything, ie. *. This is a bad example:

# blog/views.py
from django.views.generic import * # Bad idea!

Why shouldn't this import be used? If views.generic changes in unforeseen ways at some point in the future, it might cause security issues.

Back to Top