Python logoPythonv6.0INTERMEDIATE

Django

Django cheat sheet covering models, views, templates, ORM queries, URL routing, forms, and deployment patterns with code examples.

12 min read
djangopythonbackendormmvcwebfullstack
Loading your progress

Setup & Project Structure

Initialize Django projects and understand the structure

Project Setup

Create and configure a Django project

python
pip install django
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
python manage.py runserver
💡 Always use virtual environments for Django projects
⚡ django-admin for project, manage.py for apps
📌 Keep sensitive settings in .env file
🟢 Run migrations after creating models

Models & ORM

Define database models and work with Django ORM

Create Django models with fields and relationships

python
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    created = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.name
💡 Use related_name for clear reverse relationships
📌 Always define __str__ for readable admin
⚡ Add db_index=True for frequently queried fields
🟢 Use Meta class for ordering and indexes

Database queries with Django ORM

python
# Basic queries
Product.objects.all()
Product.objects.filter(price__lt=100)
Product.objects.get(id=1)
Product.objects.exclude(stock=0)

# Aggregation
from django.db.models import Count, Avg
Product.objects.aggregate(Avg('price'))
💡 Use select_related for ForeignKeys
⚡ F expressions avoid race conditions
📌 bulk_create is faster for many records
🔍 Q objects enable complex queries

Views & URLs

Handle requests with views and URL routing

Views

Function and class-based views

python
from django.shortcuts import render, get_object_or_404

def product_list(request):
    products = Product.objects.all()
    return render(request, 'products/list.html', {'products': products})

# Class-based view
from django.views.generic import ListView

class ProductListView(ListView):
    model = Product
    template_name = 'products/list.html'
💡 Use CBV for standard CRUD operations
📌 LoginRequiredMixin for auth protection
⚡ Override get_queryset() for filtering
🟢 Function views are simpler for custom logic

URL patterns and routing

python
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('products/', views.ProductListView.as_view(), name='product_list'),
    path('products/<slug:slug>/', views.product_detail, name='product_detail'),
]
💡 Use app_name for URL namespacing
📌 Path converters: str, int, slug, uuid
⚡ Include trailing slashes consistently
🟢 Use reverse() for maintainable URLs

Templates

Django template system

Template Syntax

Django template language basics

html
<!-- Variables -->
{{ product.name }}
{{ product.price|floatformat:2 }}

<!-- Tags -->
{% if product.in_stock %}
  <p>Available</p>
{% endif %}

{% for product in products %}
  {{ product.name }}
{% endfor %}
💡 Use |default filter for None values
📌 {% empty %} handles empty loops
⚡ Template inheritance with extends
🟢 Always {% load static %} for static files

Forms

Handle user input with Django forms

Create and validate forms

python
from django import forms
from .models import Product

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['name', 'price', 'description']
💡 clean_<field>() for field validation
📌 clean() for cross-field validation
⚡ Use widgets to customize HTML
🟢 commit=False to modify before saving

Admin Interface

Customize Django admin

Register and customize admin

python
from django.contrib import admin
from .models import Product

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ['name', 'price', 'stock', 'created']
    list_filter = ['status', 'created']
    search_fields = ['name', 'description']
💡 Use list_editable for inline editing
📌 prepopulated_fields for slug generation
⚡ Custom actions for bulk operations
🟢 format_html for safe HTML in admin

Authentication

User authentication and permissions

Login, logout, and permissions

python
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.decorators import login_required

@login_required
def profile(request):
    return render(request, 'profile.html')
💡 Use Django's built-in auth views
🔐 Always hash passwords automatically
📌 LoginRequiredMixin for CBV protection
⚡ @login_required decorator for FBV

Testing

Write tests for Django apps

Django Testing

Unit and integration tests

python
from django.test import TestCase, Client
from .models import Product

class ProductTestCase(TestCase):
    def setUp(self):
        Product.objects.create(name="Test", price=10)
    
    def test_product_creation(self):
        product = Product.objects.get(name="Test")
        self.assertEqual(product.price, 10)
💡 Use setUp() for test data
📌 Test both success and failure cases
⚡ Use --parallel for faster tests
🟢 Client() simulates requests

Deployment

Deploy Django to production

Deploy with gunicorn and nginx

python
# Collect static files
python manage.py collectstatic

# Gunicorn
gunicorn myproject.wsgi:application --bind 0.0.0.0:8000

# Docker
FROM python:3.11
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["gunicorn", "myproject.wsgi", "--bind", "0.0.0.0:8000"]
💡 Use environment variables for secrets
📌 Always collectstatic before deploy
⚡ Use CDN for static files
🟢 Enable caching with Redis