Django is a Python-based web framework. It provides a set of scripts for creating and working with Django projects and has a simple development webserver to test web applications at a local computer.
The basic steps to set up a new development environment for a Django application:
- Installing Python
- Setting up a virtual environment
- Installing Django
- Setting up a Django project
- Creating Django projects apps
- Installing a code editor
- Setting up git repository
For most platforms, it is possible to download the required installation files from the official python site.
The latest Ubuntu Linux LTS includes Python by default.
// to confirm this, run the command in the terminal: $ python3 -V
The Python Package Index tool (pip3) is not available by default and has to be installed.
// to install pip3 use the command below: $ sudo apt install python3-pip
// to verify that pip3 has been installed correctly: $ pip3 --version
It should show you a number like this:
pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)
Windows doesn't include Python by default. You can install it from python.org/downloads/windows. The Windows installer incorporates pip3 (the Python package manager) by default.
// to verify that Python was installed, enter one of the following commands // into the command prompt or the PowerShell: $ py -3 -V $ py --version
You can list installed packages as shown:
$ pip3 list
Setting up a virtual environment
Virtual environment isolates a Python/Django setup on a per-project basis. There are a lot of ways to isolate an environment, such as python packages (virtualenv, pipenv), Virtual Machines (VirtualBox), Containers (Docker). Python itself comes with venv for managing environments. The venv module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories.
Using the venv module to set up the virtual environment
To set up a virtual environment, create a new folder and navigate into it. We will make a virtual environment called myvenv using venv.
Run one of the following commands:
$ python -m venv myvenv
$ py -m venv myvenv
This command sets up a new virtual environment named myvenv in your current working directory.
Once you’ve created a virtual environment, you may activate it.
// to activate the virtual environment on Windows, run: $ myvenv\Scripts\activate.bat – from command promt $ myvenv\Scripts\activate.ps1 – from Windows PowerShell // to activate the virtual environment on Ubuntu (Linux) or MacOS, run: $ source myvenv/bin/activate
If the activation was successful, you see the name of your virtual environment (myvenv) at the beginning of your command prompt. It shows what virtual environment you use.
// to deactivate the virtual environment run the command: $ deactivate
Using Pip to manage python packages
You can install, upgrade, and remove packages inside the virtual environment using a program called pip. It has a number of sub-commands: “install”, “uninstall”, “freeze”, etc.
You can supply a different version number by giving the package name followed by == and the version number to get that version of a package, or you can run pip install --upgrade to upgrade the package to the latest version.
// to have the latest version of pip, run: (myvenv) $ python -m pip install --upgrade pip // to remove the packages from the virtual environment: $ pip uninstall followed by one or more package names // to display information about a particular package: $ pip show // to display all of the packages installed in the virtual environment: $ pip list // to produce a similar list of the installed packages. The output uses the format that pip install expects. $ pip freeze
pip freeze is used to put the list of the installed packages in a requirements.txt file:
(myvenv) $ pip freeze > requirements.txt (myvenv) $ cat requirements.txt
or in one line:
(myvenv) $ python -m pip freeze > requirements.txt
pip freeze doesn't show the dependencies that pip depends on. To obtain all packages you can use pip freeze --all or pip list.
Installing Django project packages
Installing Django with requirements.txt
A requirements file keeps a list of dependencies to be installed using pip install.
Create a requirements.txt file inside of the project folder, using the code editor, or the command - pip freeze > requirements.txt.
In your requirements.txt file you should add the following text:
~= - version specifier will select the latest version of the package, greater than or equal to 3.2.7
Now, run pip install -r requirements.txt to install Django:
(myvenv) $ pip install -r requirements.txt
(myvenv) $ python -m pip install -r requirements.txt
Installing Django in the command prompt with pip
Another way to install packages within a virtual environment is using pip in the command prompt.
In the command prompt, ensure your virtual environment is active, and execute the following command:
(myvenv) $ py -m pip install Django
(myvenv) $ python -m pip install Django
Testing the Django installation
To test that Django is installed in a command shell start the Python interactive interpreter by typing python for Linux or py for Windows and run the following commands:
>>> import django >>> django.VERSION
output: (3, 2, 7, 'final', 0)
// to exit the Python interactive interpreter: >>> exit()
Another way to test that Django is installed is by running the following commands:
(myvenv) $ python3 -m django --version
(myvenv) $ py -3 -m django –version or py -m django --version
Setting up a Django project
After installing Django, it is time to scaffold a new web application.
The Django framework distinguishes between projects and apps:
- A Django project is a top-level unit of web application. There is only one project and many "apps" within it.
- A Django apps is a lower-level units of web application.
Creating a django project
Activate the virtual environment.
Within the directory where you created the virtual environment run the below command (django-admin startproject <project-name>):
(myvenv) $ django-admin startproject django_project .
To avoid creating the additional top-level project folder, you can add a dot (.) at the end of the django-admin startproject command.
Starting the web server
Django comes with a built-in web server for local development. At this step, it is possible to run the server and see a standard page in the browser. You need to be in the directory that contains the manage.py file. The manage.py file is used to execute various Django commands such as running the local web server or creating a new app.
// Start the web server by running: (myvenv) $ python manage.py runserver
You can ignore the warnings about "18 unapplied migration(s)" at this point.
To check that your website is running open a browser and enter the address:
You should see Django welcome page.
Creating Django projects apps
A single Django project contains one or more apps within it.
Within the same directory where you created the virtual environment and django_project, you can create apps, media, static, and templates folders.
(myvenv) $ mkdir apps
For creating Django project apps change your directory. Go to apps folder and inside apps folder, run the following command (python manage.py startapp <appname>):
(myvenv) $ cd apps (myvenv) $ django-admin startapp pages
The newly created pages app folder contains:
- admin.py - a configuration file for the built-in Django Admin app
- apps.py - a configuration file for the app itself
- migrations folder keeps track of any changes to a models.py file, so a database and models.py stay in sync
- models.py - for defining database models which Django automatically translates into database tables
- tests.py - for app-specific tests
- views.py - to handle the request/response logic for the web app
Using the tree command, inside apps folder, we can then see our complete updated structure:
(myvenv) $ apps> tree /f
Top level files and folders of Django app:
──/pages │ admin.py │ apps.py │ models.py │ tests.py │ views.py │ __init__.py │ ├───/migrations │ │ __init__.py │ │ │ └───__pycache__ │ └───__pycache__
After creating the app we need to register the new app in settings.py
To do this:
- open django_project/settings.py with your text editor.
- find the definition for the INSTALLED_APPS list.
- add the app name that was created to INSTALLED_APPS list (apps.pages).
- open apps/pages/apps.py
- change the line name = 'pages' to name = 'apps.pages'
settings.py file has six built-in Django apps already.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.pages', # new ]
URLs, Views, Models, Templates
In Django, at least three separate files are required to power one single page.
Within an app these files are:
- the urls.py file,
- the views.py file,
- the models.py file,
- and an HTML template.
When you type in a URL in a browser, within a Django project a URL pattern is found that matches the page. The URL pattern specifies a view which then determines the content for the page and then a template for styling and basic logic. The end result is sent back to the user as an HTTP response.
The flow looks something like this:
URL -> View -> Model -> Template
To see this in action:
Update the views.py file in pages app to look as follows:
# apps/pages/views.py from django.http import HttpResponse def firstPageView(request): return HttpResponse('Hello, World!')
Create a new urls.py file and update it with the following code:
# apps/pages/urls.py from django.urls import path from .views import firstPageView urlpatterns = [ path('', firstPageView, name='home') ]
Update our django_project/urls.py file.
# django_project/urls.py from django.contrib import admin from django.urls import path, include # new urlpatterns = [ path('admin/', admin.site.urls), path('', include('apps.pages.urls')), # new ]
Now we have done it. To run the project go to the main project directory and run the following command:
(myvenv) $ python manage.py runserver
In the browser for http://127.0.0.1:8000 you should see the text “Hello, world!”
Installing code editors
There are a lot of different editors and it largely boils down to personal preference.
Python programmers use complex but extremely powerful IDEs (Integrated Development Environments), such as PyCharm, Visual Studio Code, Gedit, Atom.
Visual Studio Code
Visual Studio Code is a source code editor developed by Microsoft. It includes support for debugging, embedded Git control, syntax highlighting, intelligent code completion, snippets, and code refactoring.
Gedit is an open-source, free editor, available for all operating systems.
Setting up git repository
Git is a "version control system" used by a lot of programmers. This software can track changes to files so that it is possible to recall specific versions later.
You can download Git from Git for Windows.
Debian or Ubuntu
$ sudo apt install git
To do a one-time system set up within the command line console type:
$ git config --global user.name "Your Name" $ git config --global user.email "your_email @email.com"
Starting Git repository
Git tracks changes to a particular set of files in a code repository ("repo" for short).
To start one repo for a project open up a console and run commands in the directory with project and apps folders:
// to initialize empty Git repository inside of // a project working directory ~/project/.git/ $ git init
// to see a list of changes since the last git commit: $ git status
// to add all changes use the command add -A and then commit the changes // along with a message (-m) describing what has changed. (myvenv) $ git add -A (myvenv) $ git commit -m 'initial commit'
Connecting the Git Repository to Github:
Sign up for a free account on GitHub’s homepage and verify your email address.
Then navigate to the “Create a new repository”. During creating a new repository find git commands to push an existing repository from the command line and use them to synchronize the local directory on a computer with the remote repository on GitHub.
// To sync the local directory on our computer // with the remote repository on the GitHub website. (myvenv) $ git remote add origin https://github.com/<your_github_username>/<your_project>.git // To “push” the code to GitHub. (myvenv) $ git push -u origin master
In case of a problem, check the resources:
Configuring .gitignore file
Git will track changes to all the files and folders in this directory, but there are some files we want it to ignore.
To do this create a file called .gitignore in the base directory. Once it’s created, open the file and add folders and files to ignore. For a list of files and folders you might want to add to .gitignore use gitignore.io or a template.
References and further reading for setting up Django development environment:
- Quick Install Guide (Django docs)
- How to install Django — Complete guide (Django docs)
- How to install Django on Windows (Django docs)
- Setting up a Django development environment from Mozilla
- Django Girls Tutorial – Installation
- Virtualenv is a tool to create isolated Python environments
- venv — Creation of virtual environments
- Virtual Environments and Packages
- Version Identification and Dependency Specification
- pip install from pip documentation
- Git basic commands cheat sheet
- Gitignore (“create useful .gitignore files for your project”)
- Gitignore template
- GitHub’s collection of .gitignore file templates