Django Installation and Setup: Complete Beginner's Guide
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. In this comprehensive guide, we'll walk you through installing Django and creating your first web application.
Prerequisites
Before we start, make sure you have the following installed on your system:
- Python 3.8 or higher - Django requires Python 3.8+
- pip - Python package installer (usually comes with Python)
- Git - For version control (recommended)
Checking Your Python Installation
First, let's verify that Python is installed correctly:
# Check Python version
python --version
# or
python3 --version
# Check pip version
pip --version
# or
pip3 --version
If Python isn't installed, download it from python.org.
Step 1: Setting Up a Virtual Environment
Virtual environments are crucial for Python development as they keep project dependencies isolated.
Creating a Virtual Environment
# Navigate to your projects directory
cd ~/projects
# Create a new directory for your Django project
mkdir my-django-project
cd my-django-project
# Create a virtual environment
python -m venv django-env
# Alternative for Python 3
python3 -m venv django-env
Activating the Virtual Environment
# On macOS/Linux
source django-env/bin/activate
# On Windows
django-env\Scripts\activate
You'll know the virtual environment is active when you see (django-env)
at the beginning of your terminal prompt.
Step 2: Installing Django
With your virtual environment activated, install Django using pip:
# Install the latest stable version of Django
pip install django
# Or install a specific version
pip install django==4.2.7
# Verify the installation
django-admin --version
Alternative: Installing from requirements.txt
For team projects, create a requirements.txt
file:
Django==4.2.7
pillow==10.0.1
python-decouple==3.8
Then install:
pip install -r requirements.txt
Step 3: Creating Your First Django Project
Now let's create a new Django project:
# Create a new Django project
django-admin startproject mysite
# Navigate into the project directory
cd mysite
# View the project structure
ls -la
Project Structure Explained
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
- manage.py - Command-line utility for administrative tasks
- settings.py - Configuration for the Django project
- urls.py - URL declarations for the project
- wsgi.py - WSGI-compatible web server entry point
- asgi.py - ASGI-compatible web server entry point
Step 4: Running Your First Django Application
Let's run the development server:
# Run database migrations (creates default tables)
python manage.py migrate
# Start the development server
python manage.py runserver
Open your browser and navigate to http://127.0.0.1:8000/
. You should see the Django welcome page! 🎉
Custom Port and Host
# Run on a different port
python manage.py runserver 8080
# Run on all interfaces
python manage.py runserver 0.0.0.0:8000
Step 5: Creating Your First Django App
Django projects are made up of multiple apps. Let's create your first app:
# Create a new app called 'blog'
python manage.py startapp blog
App Structure
blog/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
Registering the App
Add your new app to INSTALLED_APPS
in mysite/settings.py
:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', # Add your app here
]
Step 6: Creating Your First View
Let's create a simple view in blog/views.py
:
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return HttpResponse("Hello, world! This is your first Django view.")
def home(request):
context = {
'title': 'Welcome to Django',
'message': 'Your Django application is running successfully!'
}
return render(request, 'blog/home.html', context)
Creating URL Configuration
Create blog/urls.py
:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('home/', views.home, name='home'),
]
Update the main mysite/urls.py
:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
path('', include('blog.urls')), # Root URL
]
Step 7: Working with Templates
Create a templates directory structure:
# Create templates directory
mkdir -p blog/templates/blog
Create blog/templates/blog/home.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{ title }}</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #2c3e50;
text-align: center;
}
.message {
color: #27ae60;
font-size: 18px;
text-align: center;
margin: 20px 0;
}
</style>
</head>
<body>
<div class="container">
<h1>{{ title }}</h1>
<p class="message">{{ message }}</p>
<p>
Congratulations! You've successfully set up Django and created your
first application.
</p>
</div>
</body>
</html>
Step 8: Database Configuration and Models
Django comes with SQLite by default, but you can configure other databases in settings.py
:
# Default SQLite configuration
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# PostgreSQL configuration example
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.postgresql',
# 'NAME': 'your_db_name',
# 'USER': 'your_db_user',
# 'PASSWORD': 'your_password',
# 'HOST': 'localhost',
# 'PORT': '5432',
# }
# }
Creating Your First Model
Add a model to blog/models.py
:
from django.db import models
from django.utils import timezone
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class Meta:
ordering = ['-created_at']
Running Migrations
# Create migration files
python manage.py makemigrations
# Apply migrations
python manage.py migrate
Step 9: Creating a Superuser
Create an admin user to access Django's admin interface:
python manage.py createsuperuser
Register your model in blog/admin.py
:
from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'created_at', 'updated_at']
list_filter = ['created_at', 'updated_at']
search_fields = ['title', 'content']
readonly_fields = ['created_at', 'updated_at']
Step 10: Essential Django Commands
Here are the most commonly used Django commands:
# Create a new project
django-admin startproject projectname
# Create a new app
python manage.py startapp appname
# Run development server
python manage.py runserver
# Create migrations
python manage.py makemigrations
# Apply migrations
python manage.py migrate
# Create superuser
python manage.py createsuperuser
# Collect static files (for production)
python manage.py collectstatic
# Open Django shell
python manage.py shell
# Check for issues
python manage.py check
# Show project URLs
python manage.py show_urls # requires django-extensions
Best Practices for Django Development
1. Use Environment Variables
Install python-decouple
for managing settings:
pip install python-decouple
Create a .env
file:
SECRET_KEY=your-secret-key-here
DEBUG=True
DATABASE_URL=sqlite:///db.sqlite3
Update settings.py
:
from decouple import config
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
2. Project Structure
myproject/
myproject/
__init__.py
settings/
__init__.py
base.py
development.py
production.py
urls.py
wsgi.py
apps/
blog/
users/
core/
static/
media/
templates/
requirements/
base.txt
development.txt
production.txt
manage.py
.env
.gitignore
3. Version Control
Create a .gitignore
file:
# Django
*.log
*.pyc
__pycache__/
db.sqlite3
media/
staticfiles/
# Environment
.env
venv/
django-env/
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
Common Issues and Solutions
Issue: ModuleNotFoundError
Problem: Python can't find Django
Solution: Make sure your virtual environment is activated and Django is installed
# Activate virtual environment
source django-env/bin/activate
# Reinstall Django
pip install django
Issue: Port Already in Use
Problem: Development server won't start
Solution: Use a different port or kill the existing process
# Use different port
python manage.py runserver 8080
# Or find and kill process using port 8000
lsof -ti:8000 | xargs kill -9
Issue: Database Errors
Problem: Migration issues
Solution: Reset migrations or check database configuration
# Reset migrations (development only)
rm -rf blog/migrations/
python manage.py makemigrations blog
python manage.py migrate
Next Steps
Now that you have Django installed and running, here are some next steps:
- Learn Django Models - Create more complex database relationships
- Master Django Forms - Handle user input securely
- Explore Django REST Framework - Build APIs
- Learn Django Testing - Write comprehensive tests
- Deploy Your Application - Use platforms like Heroku, DigitalOcean, or AWS
Useful Resources
Conclusion
Congratulations! You've successfully installed Django and created your first web application. Django's "batteries-included" philosophy means you have access to a powerful admin interface, ORM, and many other features out of the box.
Remember to always work in virtual environments, follow Django best practices, and don't hesitate to consult the excellent Django documentation when you need help.
Happy coding with Django! 🐍✨