This article is part of a series. In this series, I provide beginner tips for the Django framework. The code examples use Django 2.2, the latest stable LTS (long-term support) version of Django at the time of writing.
In this edition, we are looking at the general structure of a Django app.
What is a Django app?
A Django app is a directory containing a bunch of Python modules consisting of, but not limited to, a mix of:
- Models and migrations
- Admin configuration
- Views and URLs
- Assets (e.g., images)
- Management commands
Minimal needed files
The boilerplate Django app requires very little in terms of modules.
The files needed:
The apps module is a registry that contains the data needed for Django to register your application. Django requires this file from version
2.0 onwards. Read more about applications on https://docs.djangoproject.com/en/2.2/ref/applications/.
App file patterns
Django expects certain classes in modules with a specific name. Below are some common file patterns. Make sure to check the documentation for each feature on what to put into these modules.
If you want your app to provide data models:
your-app ├── __init__.py ├── admin.py ├── migrations │ └── __init__.py └── models.py
If you want your app to provide a web page for users:
your-app ├── __init__.py ├── assets │ └── your-app │ └── images │ └── image-used-in-template.png ├── templates │ └── your-app │ └── a-template-used-by-view.html ├── urls.py └── views.py
If you want to provide a custom management command:
your-app ├── __init__.py └── management ├── __init__.py └── commands ├── __init__.py └── custom_management_command.py
If you want to test your app:
your-app ├── __init__.py └── tests ├── __init__.py ├── test_something.py └── test_something_else.py
Installing an app
To activate your application, you must enable it in Django global settings. Installing a Django application is as easy as adding its path to
INSTALLED_APPS in settings. After installation, Django will find URLs and migrations for installed applications.
Note: Python can still access modules even if they are not part of an installed app, or not inside an app at all.
Order of installed apps