Development Environment Setup

This chapter details how to set up a Django development environment, including Python installation, virtual environment configuration, Django installation, and the selection and configuration of development tools.

System Requirements

Operating System Support

Django supports the following operating systems:

  • Windows 10/11
  • macOS 10.15+
  • Linux (Ubuntu, CentOS, Debian, etc.)

Python Version Requirements

# Python versions supported by Django 4.2 LTS
Python 3.8+   # Minimum requirement
Python 3.9    # Recommended
Python 3.10   # Recommended
Python 3.11   # Recommended
Python 3.12   # Latest supported

Python Installation

Windows System

1. Download Python from the Official Website

Visit the Python website to download the latest version:

# Download URL
https://www.python.org/downloads/windows/

# Recommended download
Python 3.11.x (stable)

2. Install Python

# Installation options
 Add Python to PATH
 Install for all users
 Associate files with Python
 Create shortcuts for installed applications
 Add Python to environment variables
 Precompile standard library

3. Verify Installation

# Open Command Prompt
python --version
# Output: Python 3.11.x

pip --version
# Output: pip 23.x.x from ...

macOS System

# Install Homebrew (if not installed)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Python
brew install python@3.11

# Verify installation
python3 --version
pip3 --version

2. Install from Official Website

# Download URL
https://www.python.org/downloads/macos/

# Verify after installation
python3 --version
pip3 --version

Linux System

Ubuntu/Debian

# Update package list
sudo apt update

# Install Python 3.11
sudo apt install python3.11 python3.11-pip python3.11-venv

# Verify installation
python3.11 --version
pip3 --version

CentOS/RHEL

# Install EPEL repository
sudo yum install epel-release

# Install Python 3.11
sudo yum install python311 python311-pip

# Verify installation
python3.11 --version
pip3 --version

Virtual Environment Configuration

Virtual environments are a best practice in Python development, allowing the creation of isolated Python environments for each project.

Why Use Virtual Environments

# Problem scenario: Different projects require different package versions
Project A: Django==3.2.0, requests==2.25.0
Project B: Django==4.2.0, requests==2.28.0

# Solution: Create separate virtual environments for each project
venv_project_a/
├── Django==3.2.0
└── requests==2.25.0

venv_project_b/
├── Django==4.2.0
└── requests==2.28.0

Creating Virtual Environments Using venv

1. Create a Virtual Environment

# Windows
python -m venv django_env

# macOS/Linux
python3 -m venv django_env

2. Activate the Virtual Environment

# Windows
django_env\Scripts\activate

# macOS/Linux
source django_env/bin/activate

# Command prompt will show after activation
(django_env) C:\Users\YourName>

3. Deactivate the Virtual Environment

# Any system
deactivate

Creating Virtual Environments Using conda

If you use Anaconda or Miniconda:

# Create a virtual environment
conda create -n django_env python=3.11

# Activate the environment
conda activate django_env

# Deactivate the environment
conda deactivate

# List all environments
conda env list

# Remove an environment
conda env remove -n django_env

Virtual Environment Best Practices

# 1. Create separate virtual environments for each project
mkdir my_django_project
cd my_django_project
python -m venv venv

# 2. Use meaningful environment names
python -m venv blog_project_env
python -m venv ecommerce_env

# 3. Add virtual environment directories to .gitignore
echo "venv/" >> .gitignore
echo "*.pyc" >> .gitignore
echo "__pycache__/" >> .gitignore

# 4. Create requirements.txt to record dependencies
pip freeze > requirements.txt

# 5. Install dependencies from requirements.txt
pip install -r requirements.txt

Django Installation

Install Django

# Ensure the virtual environment is activated
(django_env) $ pip install Django

# Install a specific version
(django_env) $ pip install Django==4.2.7

# Install the latest LTS version
(django_env) $ pip install "Django>=4.2,<5.0"

Verify Django Installation

# Check Django version
(django_env) $ python -m django --version
# Output: 4.2.7

# Or check within Python
(django_env) $ python
>>> import django
>>> django.get_version()
'4.2.7'
>>> django.VERSION
(4, 2, 7, 'final', 0)

Install Additional Dependencies

# Database drivers
pip install psycopg2-binary  # PostgreSQL
pip install mysqlclient      # MySQL
pip install cx_Oracle        # Oracle

# Image processing
pip install Pillow

# Development tools
pip install django-debug-toolbar
pip install django-extensions

# API development
pip install djangorestframework

# Create a complete requirements.txt
pip freeze > requirements.txt

Development Tool Selection

Code Editors/IDEs

// .vscode/settings.json
{
    "python.defaultInterpreterPath": "./venv/bin/python",
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "python.formatting.provider": "black",
    "python.formatting.blackArgs": ["--line-length=88"],
    "files.associations": {
        "*.html": "django-html"
    },
    "emmet.includeLanguages": {
        "django-html": "html"
    }
}

Recommended extensions:

// .vscode/extensions.json
{
    "recommendations": [
        "ms-python.python",
        "ms-python.flake8",
        "ms-python.black-formatter",
        "batisteo.vscode-django",
        "wholroyd.jinja",
        "bradlc.vscode-tailwindcss"
    ]
}

2. PyCharm Professional

# PyCharm configuration
# File -> Settings -> Project -> Python Interpreter
# Select the Python interpreter in the virtual environment

# Django support
# File -> Settings -> Languages & Frameworks -> Django
# Enable Django Support: ✓
# Django project root: /path/to/your/project
# Settings: settings.py

3. Sublime Text

// Packages/User/Python.sublime-settings
{
    "python_interpreter": "/path/to/venv/bin/python",
    "suppress_word_completions": true,
    "suppress_explicit_completions": true
}

Database Tools

1. SQLite Browser

# Install SQLite Browser
# Windows: Download installer
# macOS: brew install --cask db-browser-for-sqlite
# Ubuntu: sudo apt install sqlitebrowser

2. pgAdmin (PostgreSQL)

# Install pgAdmin
# Visit https://www.pgadmin.org/download/

3. MySQL Workbench

# Install MySQL Workbench
# Visit https://www.mysql.com/products/workbench/

Version Control

Git Configuration

# Install Git
# Windows: https://git-scm.com/download/win
# macOS: brew install git
# Linux: sudo apt install git

# Configure Git
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

# Create .gitignore file
cat > .gitignore << EOF
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
ENV/

# Django
*.log
local_settings.py
db.sqlite3
media/

# IDE
.vscode/
.idea/
*.swp
*.swo

# OS
.DS_Store
Thumbs.db
EOF

Project Structure Best Practices

my_django_project/
├── venv/                   # Virtual environment
├── requirements/           # Dependency files
│   ├── base.txt           # Base dependencies
│   ├── development.txt    # Development dependencies
│   └── production.txt     # Production dependencies
├── config/                # Configuration files
│   ├── __init__.py
│   ├── settings/
│   │   ├── __init__.py
│   │   ├── base.py        # Base settings
│   │   ├── development.py # Development settings
│   │   └── production.py  # Production settings
│   ├── urls.py
│   └── wsgi.py
├── apps/                  # Application directory
│   ├── __init__.py
│   ├── accounts/          # User account app
│   ├── blog/              # Blog app
│   └── core/              # Core app
├── static/                # Static files
├── media/                 # Media files
├── templates/             # Template files
├── locale/                # Internationalization files
├── tests/                 # Test files
├── docs/                  # Documentation
├── scripts/               # Script files
├── .env                   # Environment variables
├── .gitignore
├── manage.py
├── README.md
└── requirements.txt

Environment Variable Configuration

1. Install python-decouple

pip install python-decouple

2. Create .env file

# .env
DEBUG=True
SECRET_KEY=your-secret-key-here
DATABASE_URL=sqlite:///db.sqlite3
ALLOWED_HOSTS=localhost,127.0.0.1

# Database configuration
DB_NAME=mydatabase
DB_USER=myuser
DB_PASSWORD=mypassword
DB_HOST=localhost
DB_PORT=5432

# Email configuration
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_HOST_USER=your-email@gmail.com
EMAIL_HOST_PASSWORD=your-app-password

3. Use in settings.py

# settings.py
from decouple import config
import os

# Base configuration
DEBUG = config('DEBUG', default=False, cast=bool)
SECRET_KEY = config('SECRET_KEY')
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='').split(',')

# Database configuration
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': config('DB_NAME'),
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'HOST': config('DB_HOST', default='localhost'),
        'PORT': config('DB_PORT', default='5432'),
    }
}

# Email configuration
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_PORT = config('EMAIL_PORT', cast=int)
EMAIL_USE_TLS = True
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')

Development Tool Configuration

Django Debug Toolbar

# Install
pip install django-debug-toolbar
# settings.py
INSTALLED_APPS = [
    # ...
    'debug_toolbar',
]

MIDDLEWARE = [
    # ...
    'debug_toolbar.middleware.DebugToolbarMiddleware',
]

# Show only in DEBUG mode
INTERNAL_IPS = [
    '127.0.0.1',
]

# Configure panels
DEBUG_TOOLBAR_PANELS = [
    'debug_toolbar.panels.versions.VersionsPanel',
    'debug_toolbar.panels.timer.TimerPanel',
    'debug_toolbar.panels.settings.SettingsPanel',
    'debug_toolbar.panels.headers.HeadersPanel',
    'debug_toolbar.panels.request.RequestPanel',
    'debug_toolbar.panels.sql.SQLPanel',
    'debug_toolbar.panels.staticfiles.StaticFilesPanel',
    'debug_toolbar.panels.templates.TemplatesPanel',
    'debug_toolbar.panels.cache.CachePanel',
    'debug_toolbar.panels.signals.SignalsPanel',
    'debug_toolbar.panels.logging.LoggingPanel',
    'debug_toolbar.panels.redirects.RedirectsPanel',
    'debug_toolbar.panels.profiling.ProfilingPanel',
]
# urls.py
from django.conf import settings
from django.conf.urls import include

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        path('__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns

Django Extensions

# Install
pip install django-extensions
# settings.py
INSTALLED_APPS = [
    # ...
    'django_extensions',
]
# Useful commands
python manage.py shell_plus          # Enhanced shell
python manage.py show_urls           # Show all URLs
python manage.py validate_templates  # Validate templates
python manage.py runserver_plus      # Enhanced development server

Code Quality Tools

1. Black (Code Formatter)

# Install
pip install black

# Use
black .
black --line-length 88 .
black --check .  # Check without modifying
# pyproject.toml
[tool.black]
line-length = 88
target-version = ['py38']
include = '\.pyi?$'
extend-exclude = '''
/(
  # directories
  \.eggs
  | \.git
  | \.hg
  | \.mypy_cache
  | \.tox
  | \.venv
  | build
  | dist
)/
'''

2. Flake8 (Code Linter)

# Install
pip install flake8

# Use
flake8 .
# .flake8
[flake8]
max-line-length = 88
exclude =
    .git,
    __pycache__,
    venv,
    migrations
ignore =
    E203,  # whitespace before ':'
    W503,  # line break before binary operator

3. isort (Import Sorter)

# Install
pip install isort

# Use
isort .
isort --check-only .  # Check without modifying
# pyproject.toml
[tool.isort]
profile = "black"
multi_line_output = 3
line_length = 88

Pre-commit Hooks

# Install pre-commit
pip install pre-commit

# Create configuration file
cat > .pre-commit-config.yaml << EOF
repos:
  - repo: https://github.com/psf/black
    rev: 23.9.1
    hooks:
      - id: black
        language_version: python3.11

  - repo: https://github.com/pycqa/isort
    rev: 5.12.0
    hooks:
      - id: isort
        args: ["--profile", "black"]

  - repo: https://github.com/pycqa/flake8
    rev: 6.1.0
    hooks:
      - id: flake8

  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.4.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-added-large-files
EOF

# Install hooks
pre-commit install

Verify Environment Configuration

Create a Test Project

# Activate virtual environment
source venv/bin/activate  # Linux/macOS
# or
venv\Scripts\activate     # Windows

# Create Django project
django-admin startproject testproject
cd testproject

# Run development server
python manage.py runserver

# Visit http://127.0.0.1:8000/
# Should see Django welcome page

Environment Checklist

# check_environment.py
import sys
import django
from django.conf import settings

def check_environment():
    print("=== Django Environment Check ===")
    
    # Python version
    print(f"Python version: {sys.version}")
    
    # Django version
    print(f"Django version: {django.get_version()}")
    
    # Virtual environment check
    if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
        print("✓ Virtual environment activated")
    else:
        print("✗ Virtual environment not activated")
    
    # Installed packages
    import pkg_resources
    installed_packages = [d.project_name for d in pkg_resources.working_set]
    
    required_packages = ['django', 'pillow']
    for package in required_packages:
        if package.lower() in [p.lower() for p in installed_packages]:
            print(f"✓ {package} installed")
        else:
            print(f"✗ {package} not installed")

if __name__ == "__main__":
    check_environment()

Common Issue Resolution

1. Python Command Not Recognized

# Windows
# Ensure Python is added to PATH environment variable
# Or use py command
py --version
py -m pip install django

# macOS/Linux
# Use python3 command
python3 --version
python3 -m pip install django

2. pip Installation Fails

# Upgrade pip
python -m pip install --upgrade pip

# Use domestic mirror
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple django

# Configure permanent mirror source
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

3. Virtual Environment Activation Fails

# Windows PowerShell execution policy issue
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

# Or use cmd instead of PowerShell

4. Django Import Error

# Ensure in the correct virtual environment
which python  # Linux/macOS
where python  # Windows

# Check if Django is in Python path
python -c "import django; print(django.__file__)"

Chapter Summary

This chapter detailed the setup of a Django development environment:

Key Points:

  • Python Installation: Choose the appropriate Python version
  • Virtual Environment: Create isolated environments for each project
  • Django Installation: Install Django using pip
  • Development Tools: Select appropriate IDEs and extensions
  • Project Structure: Organize code following best practices

Best Practices:

  • Use virtual environments to isolate project dependencies
  • Configure environment variables to manage sensitive information
  • Use code quality tools to ensure code standards
  • Set up pre-commit hooks for automatic code checking
  • Create detailed requirements.txt

Development Toolchain:

  • VS Code + Python extension
  • Django Debug Toolbar
  • Black + Flake8 + isort
  • Git version control
  • Virtual environment management

In the next chapter, we will create our first Django project and learn about the basic project structure and configuration of Django.

Further Reading