How to Start a Django Project
In this tutorial, we will start a Django project from scratch.
This project will run through:
- Creating a virtual environment
- Installing packages using pip
- Creating a Django project
- Initialising a Django app
- Running the development server
- Running migrations
- Creating a superuser
- Securing your environment variables like your secret key
- Pushing to git
By the end, you will be ready to start defining models, urls and views in your app.
A repository is available here if you get stuck:
Credit to Django Girls
Setting up a Django project, particularly for the first time has a lot of steps. The Django Girls tutorial got me through it for the first time and has been a great reference for all the projects since.
If you get stuck following this walkthrough or want to read about the process in more detail, I highly recommend their tutorial.
1. Installation
Create a project directory
We are going to start a To Do list app.
$ mkdir todo$ cd todo
Create and activate a virtual environment
$ python3 -m venv todo-venv
This will create a virtual environment called ‘todo-venv’. Your virtual environment will contain files for all third-party dependencies and help you make sure you are using the correct version for each package.
Now, activate your virtual environment.
$ source todo-venv/bin/activate
Install pip
You will need pip to install python packages. Make sure you have the latest version:
$ python -m pip install — upgrade pip
Install django-admin
Now you have pip installed, you can install django-admin
$ pip install django-admin
Install pip-tools
We will need pip-tools so we can compile our requirements.
$ pip install pip-tools
2. Install Django
We will create a file to track our project requirements and use it to install Django.
Create requirements.in
Create a file to store your requirements.
$ touch requirements.in
Open your project directory in VScode:
$ code .
Now, in requirements.in
, just type ‘django’
django
Compile requirements.in
In your terminal, run the following line. This will compile requirements.txt
from requirements.in
.
$ pip-compile --output-file=requirements.txt requirements.in
The compile process will add all the additional packages required to run the packages in requirements.in
. This makes our requirements easier to manage.
Install Requirements
$ pip install -r requirements.txt
4. Start a Django project
$ django-admin startproject config
This will create a directory called config
, which contains another folder, also called config
.
Reorganise your folders
This step is optional but I prefer to get rid of that outer folder like this:
5. Create an app
You might be wondering why we named the project ‘config’ and not ‘todo’.
In Django, we structure our projects using apps. For example, in an e-commerce project you might have an apps called ‘products’, ‘ordering’ and ‘stock’ to keep code for different parts of the project separate.
I prefer to have the folder that contains settings.py
‘config’ so I can quickly tell it apart from my app folders.
This project will just need one app. We’ll call it ‘todo’.
Make sure you are in the same directory as manage.py
and run the following line.
$ django-admin startapp todo
Register the app
This is an important step. Skip this step and Django won’t recognise any of the code in your app.
Go into your config folder and open settings.py
.
Scroll down until you find a list called INSTALLED_APPS
and add the name of your new app to the list.
config/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'todo'
]
6. Start the server
Check your project is set up correctly by starting the server.
$ python manage.py runserver
You might get an error like this:
File “manage.py”, line 17
) from exc
^
SyntaxError: invalid syntax
If you get that error, reactivate your virtual environment and try again.
$ source todo-venv/bin/activate
When your server is running, open your browser and navigate to http://localhost:8000/ . You should see a screen like the image below.
7. Run Migrations
Migrations describe changes to your database. Django is a batteries-included kind of framework (it has lots of features built in to help your workflow), so it needs to create a few tables to enable these features.
To run the migrations, stop your development server using CTRL C
and run the following command:
$ python manage.py migrate
8. Create a Superuser
You will need to create a superuser so you can access the admin panel.
$ python manage.py createsuperuser
Django will prompt you for a username, email and password.
When you’ve done that, restart your dev server.
$ python manage.py runserver
Now, go back to your browser and navigate to http://localhost:8000/admin
You should be able to log in using the credentials you just set up.
If successful, you will see a screen like this:
9. Make your Secret Key secret
Install django-environ
Open requirements.in
and add django-environ
to a new line. Your file should look like this:
djangodjango-environ
Compile requirements.in
using the following command:
$ pip-compile — output-file=requirements.txt requirements.in
And then install the requirements:
pip install -r requirements.txt
It is good practice to install packages this way as it helps you keep track of your installed packages. Unlike package.json
in the JavaScript ecosystem, pip doesn’t automatically update requirements.txt
when new packages are installed.
Create a .env file
In the same directory as settings.py
, create a file called .env
In .env
, add a line for the secret key using the snippet below as an example.
Make sure there are no spaces around the equals sign!
SECRET_KEY=4335956fc5ec4f96djsk5b29414b067d8ff4b
Import your secret key into settings.py
Go to config/settings.py
Add the following code snippet:
import environ
env = environ.Env()
environ.Env.read_env()
Staying in config/settings.py
, scroll down to the line where SECRET KEY
is defined.
Replace the line with this one:
SECRET_KEY = env('SECRET_KEY')
10. Git ready
Now we have secured our secret key, we are one step closer to being able to push our project to Github.
Initialise a repository
Go to Github (or the git client of your choosing) and create a new repository.
Then, in the terminal:
$ git init
$ git remote add origin git@github.com:<username>/django-tutorial-part-one.git
Create a .gitignore
There are some files that shouldn’t be pushed to Github.
These include .env
which must be kept private and your virtual environment, todo-venv
which will waste space.
At the root of your project, create a file called .gitignore
and copy/paste in the following:
.env
__pycache__
db.sqlite3
todo-venv
This has reduced the number of tracked files from 5000 to 16. VScode may need a couple of minutes to update the source control tab.
Commit your files
Stage your files:
git add .
and then commit them
git commit -m "initial commit"
and finally,
git push origin master