Django API Reference & Cheatsheet
In this tutorial, you'll learn about Django API Reference & Cheatsheet. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. This reference covers the essential APIs and patterns you'll use daily.
What's in This Reference
- Model field types and ORM query operators
- URL patterns and view functions
- Template tags and filters
- Middleware and settings reference
- Form handling and admin customization
flowchart TD
A["Request"] --> B["URL Router"]
B --> C["Middleware"]
C --> D["View"]
D --> E["Model / ORM"]
D --> F["Template"]
E --> D
F --> G["Response"]
G --> H["Client"]
style A fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
style B fill:#fef3c7,stroke:#f59e0b,color:#78350f
style D fill:#d1fae5,stroke:#10b981,color:#064e3b
style G fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
Prerequisite: This is a reference, not a tutorial. You should already understand Django â models, views, templates, and URLs. Review the Django advanced guide for detailed explanations.
Model Field Types
| Field | Purpose |
|---|---|
CharField(max_length) |
Short text (title, name) |
TextField() |
Long text (body, description) |
IntegerField() |
Integer values |
FloatField() |
Decimal values |
BooleanField() |
True/False |
DateField() / DateTimeField() |
Dates and timestamps |
EmailField() |
Email addresses with validation |
URLField() |
URLs with validation |
FileField() / ImageField() |
File and image uploads |
ForeignKey(to) |
Many-to-one relationship |
ManyToManyField(to) |
Many-to-many relationship |
OneToOneField(to) |
One-to-one relationship |
DecimalField(max_digits, decimal_places) |
Precise decimal values |
SlugField() |
URL-friendly labels |
UUIDField() |
UUID primary keys |
ORM Query Reference
# Create
Product.objects.create(name="Widget", price=9.99)
# Read
Product.objects.get(id=1) # Single object
Product.objects.filter(price__gt=10) # Filter
Product.objects.exclude(stock=0) # Exclude
Product.objects.all() # All
Product.objects.first() / .last() # First/last
# Update
Product.objects.filter(category="books").update(price=12.99)
# Delete
Product.objects.get(id=1).delete()
Filter Operators
| Operator | Example | Description |
|---|---|---|
__exact |
name__exact="Widget" |
Exact match |
__iexact |
name__iexact="widget" |
Case-insensitive exact |
__contains |
name__contains="Wid" |
Contains |
__icontains |
name__icontains="wid" |
Case-insensitive contains |
__in |
id__in=[1, 2, 3] |
In a list |
__gt / __gte |
price__gt=10 |
Greater than (or equal) |
__lt / __lte |
price__lt=50 |
Less than (or equal) |
__startswith |
name__startswith="A" |
Starts with |
__range |
price__range=(10, 50) |
Between two values |
__isnull |
description__isnull=True |
Is NULL |
Aggregation and Annotation
from django.db.models import Count, Sum, Avg, Max, Min
# Aggregate on entire queryset
Product.objects.aggregate(avg_price=Avg("price"))
# Annotate per object (add computed field)
Category.objects.annotate(product_count=Count("products"))
Relationships
# Forward access (ForeignKey)
product.category # Access the related category
product.category.name # Access category fields
# Reverse access
category.products.all() # All products in this category
category.products.filter(price__gt=10)
# Prefetch for performance
Category.objects.prefetch_related("products").all()
URL Patterns
from django.urls import path, re_path, include
urlpatterns = [
# Simple path
path("products/", views.product_list, name="product-list"), "# Path with parameter
path("products/<int:pk>/"", views.product_detail, name="product-detail"),
# Regex path
re_path(r"^archive/(?P<year>[0-9]{4})/", views.archive),
# Include other URL configs
path("api/", include("api.urls")),
]
Path converters: str, int, slug, uuid, path.
Views
# Function-based view
from django.shortcuts import render, get_object_or_404
def product_detail(request, pk):
product = get_object_or_404(Product, pk=pk)
return render(request, "products/detail.html", {"product": product})
# Class-based view
from django.views.generic import ListView, DetailView
class ProductListView(ListView):
model = Product
template_name = "products/list.html"
context_object_name = "products"
paginate_by = 20
Templates
{# Variables #}
{{ product.name }}
{{ product.price|floatformat:2 }}
{# Tags #}
{% if products %}
{% for product in products %}
<li>{{ product.name }}</li>
{% endfor %}
{% else %}
<p>No products found.</p>
{% endif %}
{# Filters #}
{{ text|lower }}
{{ text|truncatewords:20 }}
{{ date|date:"Y-m-d" }}
{# Inheritance #}
{% extends "base.html" %}
{% block content %}...{% endblock %}
{# Static files #}
{% load static %}
<img src="{% static 'images/logo.png' %}">
Middleware
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
Common Mistakes
1. Forgetting Migrations
After changing models, run python manage.py makemigrations and python manage.py migrate.
2. Not Using get_object_or_404
Using Model.objects.get(pk=id) raises Model.DoesNotExist if not found. Use get_object_or_404(Model, pk=id) to return a 404.
3. Forgetting @login_required
Protect views with from django.contrib.auth.decorators import login_required.
4. N+1 Queries
Use select_related for ForeignKeys and prefetch_related for ManyToManyFields.
FAQ
{{< faq question="What's the difference between get() and filter()?">}}
get() returns a single object (raises error if 0 or multiple). filter() returns a QuerySet (can be empty or have many results).
{{< /faq >}}
{{< faq question="When should I use class-based views vs function-based views?">}} Use FBVs for simple or custom views. Use CBVs when you need built-in features like pagination, form handling, or CRUD operations. CBVs reduce boilerplate but can be harder to customize. {{< /faq >}}
Try It Yourself
Create a model, add it to admin, write a view, and create a template. This is the classic Django workflow that covers 80% of what you'll do.
What's Next
| Topic | Description | Link |
|---|---|---|
| Django Advanced | REST APIs, Celery, Caching | {{< ref "../django/advanced" >}} |
| Flask Reference | Compare with Flask | {{< ref "../flask/reference" >}} |
| FastAPI Reference | Compare with FastAPI | {{< ref "../fastapi/reference" >}} |
| SQL Databases | Learn database design | SQL |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro