Setting Up a Django Development Environment
A stable development environment is a prerequisite for building websites with Django. The initial setup, while potentially daunting for newcomers, follows a straightforward sequence akin to initializing CLI projects for other frameworks.
Installing Python
Django is built on Python. Begin by verifying or installing a Python interpreter. Download the official installer from the Python website under the "Downloads" section, which provides system-specific packages.
During installation on Windows, enable the options "Use admin privileges when installing py.exe" and "Add python.exe to PATH" before proceeding. macOS users can typically accept the default settings.
After installation, confirm the Python version using a terminal command:
python --version
# Alternatively
python -V
# On macOS, you might need:
# python3 --version
A successful installation will output the version number.
Creating and Managing a Virtual Environment
Using a virtual environment is recommended to manage project-specific dependencies independently, preventing conflicts between different project requirements.
Python includes the venv module for this purpose. Navigate to your project directory and execute:
python -m venv environment_name
For instance, python -m venv myenv creates a virtual environment named myenv.
Activating the Environment
The activation script location differs by operating system.
- macOS/Linux:
source myenv/bin/activate - Windows:
myenv\Scripts\activate
Upon successful activation, the terminal prompt will typically prefix the environment name.
Deactivating the Environment
To exit the virtual environment and return to the global system context, run:
deactivate
Installing Django
With the virtual environment active, install Django using pip.
pip install django
# On some macOS systems, use pip3
# pip3 install django
To install a specific version, specify it:
pip install django==4.1
Verify the installation and check installed packages:
django-admin --version
pip list
Initializing a Django Project
Use the django-admin command-line tool to generate a new project structure.
django-admin startproject project_name
Example: django-admin startproject my_site creates a directory named my_site containing the project boilerplate.
Running the Development Server
Navigate into the project directory and start the built-in development server.
cd my_site
python manage.py runserver
The terminal will display a confirmation message with a default address, usually http://127.0.0.1:8000/. Open this URL in a web browser to see the default Django welcome page.
To use a different port, specify it as an argument:
python manage.py runserver 9000