Django
Django cheat sheet covering models, views, templates, ORM queries, URL routing, forms, and deployment patterns with code examples.
Other Python Sheets
Setup & Project Structure
Initialize Django projects and understand the structure
Create and configure a Django project
pip install django
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
python manage.py runserverModels & ORM
Define database models and work with Django ORM
Create Django models with fields and relationships
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.nameDatabase queries with Django ORM
# 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'))Views & URLs
Handle requests with views and URL routing
Function and class-based views
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'URL patterns and routing
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'),
]Templates
Django template system
Django template language basics
<!-- Variables -->
{{ product.name }}
{{ product.price|floatformat:2 }}
<!-- Tags -->
{% if product.in_stock %}
<p>Available</p>
{% endif %}
{% for product in products %}
{{ product.name }}
{% endfor %}Forms
Handle user input with Django forms
Create and validate forms
from django import forms
from .models import Product
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'price', 'description']Admin Interface
Customize Django admin
Register and customize admin
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']Authentication
User authentication and permissions
Login, logout, and permissions
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')Testing
Write tests for Django apps
Unit and integration tests
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)Deployment
Deploy Django to production
Deploy with gunicorn and nginx
# 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"]