Django Cheatsheet

December 17, 2025
20 min read
Lalit Mahato
Django Cheatsheet

Django Cheatsheet

This cheatsheet covers commonly used Django commands, core concepts, and practical snippets for day‑to‑day development.


1. Project & App Setup

Create Virtual Environment

python -m venv venv
source venv/bin/activate  # Linux/Mac
venv\\Scripts\\activate     # Windows

Install Django

pip install django

Create Project

django-admin startproject project_name
cd project_name

Create App

python manage.py startapp app_name

Run Development Server

python manage.py runserver
python manage.py runserver 0.0.0.0:8000

2. Settings & Configuration

Register App

INSTALLED_APPS = [
    'app_name',
]

Database (PostgreSQL Example)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'db_name',
        'USER': 'user',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

Static & Media Files

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

3. Models

Basic Model

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

Common Fields

  • CharField

  • TextField

  • IntegerField

  • BooleanField

  • DateField / DateTimeField

  • ForeignKey

  • OneToOneField

  • ManyToManyField


4. Migrations

python manage.py makemigrations
python manage.py migrate
python manage.py showmigrations
python manage.py sqlmigrate app_name 0001

5. Django ORM (Queries)

Create

Product.objects.create(name="Book", price=100)

Read

Product.objects.all()
Product.objects.get(id=1)
Product.objects.filter(price__gte=100)

Update

product = Product.objects.get(id=1)
product.price = 120
product.save()

Delete

Product.objects.filter(id=1).delete()

Query Helpers

from django.db.models import Q, Count, Sum

Product.objects.filter(Q(price__gt=100) | Q(name__icontains="pen"))
Product.objects.aggregate(total=Sum('price'))

6. Admin Panel

Create Superuser

python manage.py createsuperuser

Register Model

from django.contrib import admin
from .models import Product

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ('name', 'price')

7. Views

Function‑Based View (FBV)

from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello World")

Class‑Based View (CBV)

from django.views import View
from django.http import HttpResponse

class HomeView(View):
    def get(self, request):
        return HttpResponse("Hello World")

8. URLs

App URLs

from django.urls import path
from .views import home

urlpatterns = [
    path('', home, name='home'),
]

Include in Project URLs

from django.urls import path, include

urlpatterns = [
    path('', include('app_name.urls')),
]

9. Templates

Template Settings

TEMPLATES = [
    {
        'DIRS': [BASE_DIR / 'templates'],
    },
]

Template Syntax

{{ variable }}
{% if user.is_authenticated %}
{% for item in items %}
{% endfor %}

10. Forms

ModelForm

from django.forms import ModelForm
from .models import Product

class ProductForm(ModelForm):
    class Meta:
        model = Product
        fields = '__all__'

11. Authentication

Login Required

from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):
    pass

Custom User Model

from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    phone = models.CharField(max_length=20, blank=True)

12. Middleware

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
]

13. Signals

from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Product

@receiver(post_save, sender=Product)
def product_created(sender, instance, created, **kwargs):
    if created:
        print("Product Created")

14. Django REST Framework (Quick)

Install

pip install djangorestframework

Serializer

from rest_framework import serializers
from .models import Product

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

API View

from rest_framework.views import APIView
from rest_framework.response import Response

class ProductAPI(APIView):
    def get(self, request):
        return Response({"status": "ok"})

15. Management Commands

python manage.py shell
python manage.py collectstatic
python manage.py flush
python manage.py check

16. Deployment Essentials

  • DEBUG = False

  • Set ALLOWED_HOSTS

  • Use .env for secrets

  • Configure Gunicorn / uWSGI

  • Nginx as reverse proxy


17. Useful Django Packages

  • django‑rest‑framework

  • django‑filter

  • django‑cors‑headers

  • django‑allauth

  • celery

  • django‑debug‑toolbar


18. Common Shortcuts

get_object_or_404(Model, id=1)
redirect('url_name')
reverse('url_name')

19. Security Basics

  • CSRF protection enabled

  • Use Django ORM (avoid raw SQL)

  • Validate user input

  • Hash passwords (default)


20. Debugging

python manage.py shell_plus  # django‑extensions

This cheatsheet is suitable for quick reference during Django development and interviews.

Tags

django
Lalit Mahato

Lalit Mahato

Software Engineer | Machine Learning Enthusiast

Innovative and results-driven software developer with 5+ years of experience in designing, developing, and deploying high-quality software solutions. Proficient in various programming languages and technologies, with a keen interest in …

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Search

Categories

Related Posts

Emails in Django
Emails in Django

Dec 18, 2025

Read More
Django-specific OWASP guidelines
Django-specific OWASP guidelines

Dec 17, 2025

Read More
Custom Decoraators
Custom Decoraators

Dec 14, 2025

Read More