Django's "batteries-included" philosophy means you can build applications quickly without reinventing the wheel.
🔒
Security
Django includes robust security features by default, helping protect against common vulnerabilities.
📈
Scalability
Used by Instagram, Pinterest, and Dropbox, Django can scale to handle millions of users.
Django Overview
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the Model-View-Template (MVT) architectural pattern, which is similar to MVC (Model-View-Controller) but with Django-specific terminology.
URL Dispatcher
View
Model
Template
When a request comes to a Django application:
The URL dispatcher determines which view should handle the request
The view interacts with the model to retrieve or update data
The model handles data validation and database operations
The view passes data to a template for rendering
The rendered HTML is returned to the user
Getting Started with Django
Prerequisites
Before you start, make sure you have:
Python 3.8 or newer installed
Basic knowledge of Python programming
Understanding of basic web concepts (HTTP, HTML, CSS)
A text editor or IDE (VS Code, PyCharm, etc.)
Installation
The recommended way to install Django is using pip, the Python package manager:
# Create a virtual environment
python -m venv venv
# Activate the virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
# Install Django
pip install django
Tip: Always use a virtual environment for your Django projects. This isolates dependencies for each project, preventing conflicts between different projects.
Creating Your First Django Project
Let's create a simple blog application to learn the basics:
# Create a new Django project
django-admin startproject myblog
# Navigate to the project directory
cd myblog
# Start the development server
python manage.py runserver
You should now be able to visit http://127.0.0.1:8000/ in your browser and see Django's welcome page.
Project Structure
Your new Django project will have the following structure:
myblog/ # Root project directory
manage.py # Command-line utility for administrative tasks
myblog/ # Project package
__init__.py # Empty file that tells Python this is a package
settings.py # Project settings/configuration
urls.py # URL declarations for the project
asgi.py # ASGI configuration for deployment
wsgi.py # WSGI configuration for deployment
Creating an App
Django projects are divided into "apps" - modular components that represent different parts of your application:
# Create a blog app
python manage.py startapp blog
After creating the app, you need to register it in your project's settings. Open myblog/settings.py and add 'blog' to the INSTALLED_APPS list:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', # Add your new app here
]
Models and Database
What are Models?
Models are Python classes that define the structure of your database tables. Each model typically corresponds to a single database table.
Creating Models
Let's create models for our blog application. Open blog/models.py and add:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "Categories"
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
def __str__(self):
return self.title
Common Field Types
CharField - For small to medium-sized strings
TextField - For longer text
IntegerField - For integers
FloatField - For floating-point numbers
BooleanField - For true/false values
DateTimeField - For date and time
ForeignKey - For one-to-many relationships
ManyToManyField - For many-to-many relationships
OneToOneField - For one-to-one relationships
FileField - For file uploads
ImageField - For image uploads
Migrations
After defining your models, you need to create and apply migrations to update your database schema:
Tip: Run migrations every time you change your models to keep your database schema in sync with your code.
Django Admin
Django comes with a powerful admin interface that allows you to manage your data. To use it, first create a superuser:
python manage.py createsuperuser
Then, register your models in blog/admin.py:
from django.contrib import admin
from .models import Category, Post
admin.site.register(Category)
admin.site.register(Post)
Now you can access the admin interface at http://127.0.0.1:8000/admin/ and manage your blog posts and categories.
Views and URL Patterns
What are Views?
Views are Python functions or classes that receive a web request and return a web response. Views access data through models and pass it to templates for rendering.
Creating Function-Based Views
Let's create views for our blog app. Open blog/views.py and add:
Then, update the project's main URL configuration in myblog/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
Class-Based Views
Django also supports class-based views, which can help organize code and provide reusable functionality:
from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
model = Post
template_name = 'blog/home.html' # /_.html
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5
class PostDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'
To use class-based views, update your URL patterns:
from django.urls import path
from . import views
from .views import PostListView, PostDetailView
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('post//', PostDetailView.as_view(), name='post-detail'),
path('category//', views.category_posts, name='category-posts'),
]
Templates
Template Basics
Templates are HTML files with Django Template Language (DTL) that allow you to dynamically generate HTML. Create the following directory structure for templates:
{% raw %}{{ value|default:"" }}{% endraw %} - Default value if empty
{% raw %}{{ value|truncatewords:30 }}{% endraw %} - Limit words
{% raw %}{{ value|date:"F j, Y" }}{% endraw %} - Format date
Forms and User Input
Django Forms
Django forms help you handle user input, validation, and security. Create a blog/forms.py file:
from django import forms
from .models import Post, Category
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content', 'category']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}),
'category': forms.Select(attrs={'class': 'form-control'}),
}
Creating a New Post View
Add a view to handle form submission:
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import PostForm
@login_required
def create_post(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('post-detail', post_id=post.id)
else:
form = PostForm()
return render(request, 'blog/create_post.html', {'form': form, 'title': 'Create Post'})
{% extends 'blog/base.html' %}
{% block title %}
{{ title }} - My Blog
{% endblock %}
{% block content %}
Create New Post
{% endblock %}
Security Note: Always include the {% raw %}{% csrf_token %}{% endraw %} tag in your forms to protect against Cross-Site Request Forgery attacks.
Form Validation
Django automatically validates form input based on model fields. You can add custom validation by overriding the clean method:
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content', 'category']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}),
'category': forms.Select(attrs={'class': 'form-control'}),
}
def clean_title(self):
title = self.cleaned_data.get('title')
if len(title) < 5:
raise forms.ValidationError("Title must be at least 5 characters long.")
return title
User Authentication
User Registration
Django's authentication system makes it easy to handle user accounts. Create a new app for user management:
python manage.py startapp users
Add 'users' to INSTALLED_APPS in settings.py.
Create a registration form in users/forms.py:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
Create views in users/views.py:
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}! You can now log in.')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
Add URL patterns in myblog/urls.py:
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from users import views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
path('', include('blog.urls')),
]
Create templates for user authentication in users/templates/users/.
Tip: Django's built-in authentication views handle login, logout, password reset, and more. You just need to provide templates.
Additional Resources
Official Django Documentation
Comprehensive and well-organized documentation for Django.