Start your first web app with our Django Cheat Sheet
When it comes to fullstack web development in Python, there is no framework that brings more style and packs more power than Django.
Django offers a wide range of ready-to-use packages, benefits from Python’s popularity, scales like a dream and enables the creation of a self-intuitive admin panel.
💡 Read about how to build a Django admin panel with Forest and checkout our guide to Django migrations in Python.
Standing as one of the most used coding languages in the world, we thought it’d be relevant to provide our Pythonistas – or simple enthusiasts – with a little Django cheat sheet.
⚠️ Virtual environment ⚠️
Before getting started, let us address the elephant in the Django room [especially for new comers]:
To “venv’, or not to “venv”?
Shortcut ⇒ venv!
First of all, isolating a project is always a good thing. Also, running Django might make your bump into several “permission denied” errors.
Using a virtual environment to install Django is often considered a safer bet since your user doesn't have access to install into shared directories.
A virtual env is an isolated environment with its own installation directories that your user has full permissions to. This allows you to install a custom version of Python if you wish to [and its different packages]. It is like Docker or Virtualbox, but Python specific.
This solves the issue with permissions and enables you to test the same thing on different versions of the dependencies without doing it on different systems.
Moving on, the Django way.
Installing and updating Django
As explained, we will make sure to isolate our project before running Django.
Creating a directory for your Django project
# Create your project folder
$ mkdir your_project_name
# Access it
$ cd your_project_name
Once your directory is created, initiate a Python virtual environment to install Django
# Create Python virtual env
$ python3 -m venv venv
# Activate virtual env
$ source venv/bin/activate
if you wish to deactivate it, simply hit the following
$ deactivate
Now install Django in your venv
# Install django (~= same as 3.1.*)
$ pip install django~=3.1.0
You can see the steps illustrated below
I recommend to make sure that you are running the latest Django version. There’s no better way to do so than to clone Django’s repo itself.
git clone <https://github.com/django/django.git>
Requirements
# Create a requirements file that lists all your project's dependencies
~$ pip freeze > requirements.txt
# Install your project requirements (if a requirements file exist)
~$ pip install -r requirements.txt
This requirement txt is paramount for all Django projects. It usually is located in the root directory of your project.
It is used for specifying what Python packages are required to run the project you are working on.
It must be looking like this ⇒
Let’s start a new project now
# New django project (from your_project_name folder)
$ django-admin startproject your_project_name .
django-admin working its magic
We can see the Django project created
Start server to check that your Django project was initiated properly.
$ python manage.py runserver
So far so good
Let’s take a look at our configuration from settings.py [toggle down please 🙂]
"""
Django settings for cheat_sheet project.
Generated by 'django-admin startproject' using Django 3.1.14.
For more information on this file, see
<https://docs.djangoproject.com/en/3.1/topics/settings/>
For the full list of settings and their values, see
<https://docs.djangoproject.com/en/3.1/ref/settings/>
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See <https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/>
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'tm+!2*u88e9&)x&4gl0&$h$+i8(_ouhb8nvga-&kgbas*zunoa'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'cheat_sheet.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'cheat_sheet.wsgi.application'
# Database
# <https://docs.djangoproject.com/en/3.1/ref/settings/#databases>
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
If you are ever interested in the structure of a django project in general, we found two articles to be relevant: here and there
django-admin Vs manage.py
Manage.py is basically a Django command-line utility that resembles django-admin commands, but that points within a project. towards the settings.py file we mention a couple of sections ago.
Some frequent commands:
- python manage.py startapp
- python manage.py makemigrations
- python manage.py migrate
- python manage.py runserver
Create a Django app: MVC becomes MTV
Once you have created your Django project with the relevant files and settings, you may create your own Django app.
# Create app (from your_project_name folder)
$ python manage.py startapp app_name
The inside will look like this
If like me, you come from a rather strict MVC (Model-View-Controller) background, then Django might throw you off a bit a first.
Unlike Ruby-on-Rails – about which we wrote a cheat sheet as well – Django does not initiate a “controller” per se when prompted tostartapp
– we see a “models” file and a “views” file, but no controller.
The team behind the Django framework tends to refer to “MTV” (Model, Template, View) rather than MVC, like many other web dev community do – here is their explanation.
Migration 🦆
Migration in Django is a substantial topic, this is why we’ve decided to dedicate an entire article about it.
If that is not enough, you can check the official documentation, or this article that we found rather explanatory.
Either way, happy reading!
Moving on.
Recap
We have covered the need for a virtual environment when using Django – and even stepped into a heated debate within the community as there is no general consensus on the matter.
We have seen how to initiate a project up from setting up the base up to starting the app. We have mentioned some key elements (requirements.txt) and differences in commands (python-admin/manage.py).
The next article will cover the initiation of the Database with all relevant migration manipulations, and the basic implementation of the Django MTV (MVC) architecture.
To check our latest articles, head to the Forest Admin blog.
Here's a list of all our Django-related articles 😉:
- The guide to Django migrations in Python
- How to build a Django Admin Panel
- Forest Admin: Django Admin Alternative