To build a Django web application, you first need the Django source code. Like most well-known Python frameworks, Django is available to install as a package, via pip
.
Step 1: Begin by opening a terminal.
~
→
Step 2: Next, navigate to the directory where you usually keep your projects. If you don’t have such a directory, now is a good time to create one! It will be different for everyone - it could be ~/projects/, ~/dev/, ~/code/ - it’s really up to you.
For me, I would go to:
~
→ cd projects/
~/projects
→
Step 3: Once you’re there, let’s create a Django web application directory, and then navigate into it:
~/projects
→ mkdir django-web-app
~/projects
→ cd django-web-app
~/projects/django-web-app
If you’re tracking this project in Git (and I highly recommend you do!), then this is where you'll initialize your repository.
~/projects/django-web-app
→ git init
Initialized empty Git repository in /Users/yourname/projects/django-web-app/.git/
Step 4: Next, we’ll create a virtual environment to keep the project’s packages isolated from other projects.
This is the first time using the python
command. Before you do this, be sure to check that your version of Python is one of those supported by the latest version of Django:
~/projects/django-web-app
→ python --version
Python 3.9.2
~/projects/django-web-app
→ python -m venv env
~/projects/django-web-app
→ ls
env
Using the ls
command, you can see that the virtual environment has been created inside the django-web-app
directory.
We don’t include installed packages in our repo, so add env/
to your .gitignore if you are using Git.
Step 5: Now let’s activate the virtual environment:
~/projects/django-web-app
→ source env/bin/activate
(env) ~/projects/django-web-app
Now when you do a pip install
, the package will not be installed into the global environment - instead, it will be installed into the virtual environment.
Step 6: And with that, let’s use pip
to install Django:
# (env) ~/projects/django-web-app
→ pip install django
...
Successfully installed django-3.1.7
The Django package is installed, along with some dependencies - packages that Django itself requires to work.
Let’s keep track of all of these packages in a requirements.txt file. There’s a neat shortcut to do this:
→ pip freeze > requirements.txt
The file is created with the listed dependencies:
# ~/projects/django-web-app/requirements.txt
asgiref==3.3.1
Django==3.1.7
pytz==2021.1
sqlparse==0.4.1
If you’re having issues with anything from the above section, check out the screencast to check you’re set up correctly.
With Django installed, you’re ready to start using it!