Setting up Django properly is crucial for a smooth development experience. This guide covers multiple installation methods, environment setup, and best practices for professional Django development.
Python Version
python --version or python3 --versionOperating System Support
Development Tools
# Check Python version
python --version
# or
python3 --version
# Check pip (Python package manager)
pip --version
# or
pip3 --version
Expected Output:
Python 3.11.5
pip 23.2.1 from /usr/local/lib/python3.11/site-packages/pip (python 3.11)
Virtual environments isolate your project dependencies, preventing conflicts between different projects.
Create Virtual Environment:
# Navigate to your project directory
mkdir my_django_project
cd my_django_project
# Create virtual environment
python -m venv django_env
# Alternative for Python 3
python3 -m venv django_env
Activate Virtual Environment:
On Windows:
# Command Prompt
django_env\Scripts\activate
# PowerShell
django_env\Scripts\Activate.ps1
# Git Bash
source django_env/Scripts/activate
On macOS/Linux:
source django_env/bin/activate
Verify Activation:
# Your prompt should show (django_env)
(django_env) $ which python
# Should point to virtual environment
Install Django:
# Install latest stable version
pip install django
# Install specific version
pip install django==4.2.7
# Install LTS version
pip install "django>=4.2,<5.0"
Verify Installation:
python -m django --version
# or
django-admin --version
Install virtualenv:
pip install virtualenv
Create and activate:
# Create environment
virtualenv django_env
# Activate (same as venv above)
source django_env/bin/activate # macOS/Linux
django_env\Scripts\activate # Windows
Install Miniconda/Anaconda first, then:
# Create environment with Python and Django
conda create -n django_env python=3.11 django
# Activate environment
conda activate django_env
# Or install Django in existing environment
conda activate django_env
conda install django
Pipenv combines pip and virtualenv functionality:
Install pipenv:
pip install pipenv
Create project and install Django:
mkdir my_django_project
cd my_django_project
# Install Django and create Pipfile
pipenv install django
# Activate shell
pipenv shell
# Run commands in environment
pipenv run python manage.py runserver
Poetry provides dependency management and packaging:
Install Poetry:
# Using pip
pip install poetry
# Using curl (macOS/Linux)
curl -sSL https://install.python-poetry.org | python3 -
Create project:
mkdir my_django_project
cd my_django_project
# Initialize project
poetry init
# Add Django dependency
poetry add django
# Activate environment
poetry shell
For consistent environments across different systems:
Create Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
Create docker-compose.yml:
version: '3.8'
services:
web:
build: .
ports:
- "8000:8000"
volumes:
- .:/app
environment:
- DEBUG=1
depends_on:
- db
db:
image: postgres:15
environment:
POSTGRES_DB: django_db
POSTGRES_USER: django_user
POSTGRES_PASSWORD: django_pass
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
Run with Docker:
# Build and start
docker-compose up --build
# Run Django commands
docker-compose exec web python manage.py migrate
docker-compose exec web python manage.py createsuperuser
Create a requirements.txt file:
# Core Django
Django==4.2.7
# Development tools
django-debug-toolbar==4.2.0
django-extensions==3.2.3
# Database
psycopg2-binary==2.9.7 # PostgreSQL
# or
# mysqlclient==2.2.0 # MySQL
# Environment management
python-decouple==3.8
# API development
djangorestframework==3.14.0
# Testing
pytest-django==4.5.2
factory-boy==3.3.0
# Code quality
black==23.9.1
flake8==6.1.0
isort==5.12.0
Install all packages:
pip install -r requirements.txt
Create .env file for sensitive settings:
# .env
SECRET_KEY=your-secret-key-here
DEBUG=True
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
ALLOWED_HOSTS=localhost,127.0.0.1
Install python-decouple:
pip install python-decouple
Use in settings.py:
from decouple import config
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='').split(',')
Install Extensions:
Create .vscode/settings.json:
{
"python.defaultInterpreterPath": "./django_env/bin/python",
"python.linting.enabled": true,
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"python.formatting.provider": "black",
"python.sortImports.args": ["--profile", "black"],
"editor.formatOnSave": true,
"files.associations": {
"*.html": "django-html"
}
}
No additional setup required. Django uses SQLite by default.
Install PostgreSQL:
# Ubuntu/Debian
sudo apt-get install postgresql postgresql-contrib
# macOS with Homebrew
brew install postgresql
# Windows - Download from postgresql.org
Create Database:
# Connect to PostgreSQL
sudo -u postgres psql
# Create database and user
CREATE DATABASE django_db;
CREATE USER django_user WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE django_db TO django_user;
\q
Install Python Driver:
pip install psycopg2-binary
Configure in settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'django_db',
'USER': 'django_user',
'PASSWORD': 'your_password',
'HOST': 'localhost',
'PORT': '5432',
}
}
Install MySQL:
# Ubuntu/Debian
sudo apt-get install mysql-server
# macOS with Homebrew
brew install mysql
# Windows - Download from mysql.com
Install Python Driver:
pip install mysqlclient
Configure in settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_db',
'USER': 'django_user',
'PASSWORD': 'your_password',
'HOST': 'localhost',
'PORT': '3306',
}
}
# Create new Django project
django-admin startproject testproject
cd testproject
# Run initial migration
python manage.py migrate
# Create superuser
python manage.py createsuperuser
# Start development server
python manage.py runserver
Development Server: http://127.0.0.1:8000/Admin Interface: http://127.0.0.1:8000/admin/
Expected Output:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
November 15, 2024 - 10:30:45
Django version 4.2.7, using settings 'testproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
# test_installation.py
import django
from django.conf import settings
from django.test.utils import get_runner
if __name__ == "__main__":
print(f"Django version: {django.get_version()}")
# Configure minimal settings
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
],
SECRET_KEY='test-key-only'
)
django.setup()
# Run a simple test
from django.contrib.auth.models import User
print("Django is working correctly!")
Run test:
python test_installation.py
Problem: Permission denied when installing packages Solution:
# Use --user flag
pip install --user django
# Or fix pip permissions (macOS/Linux)
sudo chown -R $(whoami) ~/.local
Problem: Multiple Python versions causing issues Solution:
# Use specific Python version
python3.11 -m venv django_env
# Or use pyenv to manage Python versions
curl https://pyenv.run | bash
pyenv install 3.11.5
pyenv global 3.11.5
Problem: Virtual environment commands not working Solution:
# Ensure you're in the right directory
pwd
# Check if virtual environment exists
ls django_env/
# Recreate if necessary
rm -rf django_env
python -m venv django_env
Problem: django-admin command not recognized
Solution:
# Ensure virtual environment is activated
source django_env/bin/activate
# Check if Django is installed
pip list | grep Django
# Use Python module syntax
python -m django startproject myproject
Problem: Can't connect to PostgreSQL/MySQL Solution:
# Check database service status
sudo systemctl status postgresql # Linux
brew services list | grep postgres # macOS
# Test connection manually
psql -h localhost -U django_user -d django_db
# Check firewall settings
sudo ufw status # Linux
# Never install Django globally
pip install django # ❌ Don't do this
# Always use virtual environments
python -m venv django_env
source django_env/bin/activate
pip install django # ✅ Do this
# requirements.txt - Pin exact versions for reproducibility
Django==4.2.7
psycopg2-binary==2.9.7
python-decouple==3.8
# requirements-dev.txt - Development dependencies
-r requirements.txt
django-debug-toolbar==4.2.0
pytest-django==4.5.2
black==23.9.1
# settings/base.py
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent.parent
# settings/development.py
from .base import *
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
# settings/production.py
from .base import *
DEBUG = False
ALLOWED_HOSTS = ['yourdomain.com']
# Django
*.log
*.pot
*.pyc
__pycache__/
local_settings.py
db.sqlite3
media/
# Virtual Environment
django_env/
venv/
env/
# IDE
.vscode/
.idea/
*.swp
*.swo
# Environment Variables
.env
.env.local
Create a README.md:
# My Django Project
## Setup
1. Clone repository
2. Create virtual environment: `python -m venv django_env`
3. Activate environment: `source django_env/bin/activate`
4. Install dependencies: `pip install -r requirements.txt`
5. Copy `.env.example` to `.env` and configure
6. Run migrations: `python manage.py migrate`
7. Create superuser: `python manage.py createsuperuser`
8. Start server: `python manage.py runserver`
## Development
- Run tests: `python manage.py test`
- Format code: `black .`
- Check linting: `flake8`
python -m django --version
pip show django
# Backup your project first
git commit -am "Backup before Django upgrade"
# Check compatibility
pip install django-upgrade
django-upgrade --target-version 4.2 .
# Upgrade Django
pip install --upgrade django
# Update requirements.txt
pip freeze > requirements.txt
# Test thoroughly
python manage.py check
python manage.py test
Your Django installation is now complete and ready for development. The next step is creating your first Django project.
Project Structure Overview
Understanding Django's project structure is crucial for effective development. Django organizes code into projects and apps, each serving specific purposes in your web application architecture.
Creating Your First Django Project
Creating a Django project is the first step in building web applications with Django. This guide covers project creation, initial configuration, and best practices for setting up a professional Django development environment.