Django Cheat-Sheet: From Scratch to Advanced Features.

Jagrit Thapar

1058 words • 6 min read


Django Logo

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. This cheat-sheet will guide you through creating a Django project from scratch, adding applications, creating static and dynamic views, setting up a database, utilizing Django's ORM for complex queries, and more. By the end of this guide, you will have a solid understanding of Django's core concepts and how to use them effectively.

Setting Up Django

Installing Django

Ensure you have Python installed, then install Django using pip:

pip install django

Creating a New Django Project

To create a new Django project, run:

django-admin startproject myproject

Navigate into your project directory:

cd myproject

Running the Development Server

Start the development server with:

python runserver

You can access the development server at

Creating and Adding an App

Creating a New App

Create a new app within your project:

python startapp myapp

Registering the App

Add your new app to the INSTALLED_APPS list in myproject/


Creating Static Views

Basic View

Create a simple view in myapp/

from django.http import HttpResponse
def home(request):
    return HttpResponse("Hello, World!")

Mapping the URL

Map the URL to your view in myapp/

from django.urls import path
from .views import home
urlpatterns = [
    path('', home, name='home'),

Ensure myapp/ is included in the project’s

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('', include('myapp.urls')),

Creating Dynamic Views

Template Rendering

Create a template in myapp/templates/myapp/home.html:

<!DOCTYPE html>
    <h1>Hello, {{ name }}!</h1>

Update the view to use a template:

from django.shortcuts import render
def home(request):
    context = {'name': 'Django'}
    return render(request, 'myapp/home.html', context)

Adding a Database

Configuring the Database

By default, Django uses SQLite, configured in myproject/

    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / "db.sqlite3",

Creating Models with Various Field Types

In myapp/, define your models using different field types:

from django.db import models
class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    available = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    release_date = models.DateField()
    image = models.ImageField(upload_to='images/')
    file = models.FileField(upload_to='files/')
    def __str__(self):

Making Migrations

Create and apply migrations:

python makemigrations
python migrate

Django ORM and Data Fetching

Adding Data

You can add data using the Django admin or shell:

python shell
from myapp.models import Item
Item.objects.create(name="Item 1", description="This is item 1.", price=19.99, available=True, release_date='2024-06-01')

Fetching Data

In myapp/, fetch and display data:

def items(request):
    items = Item.objects.all()
    return render(request, 'myapp/items.html', {'items': items})

Create a template myapp/templates/myapp/items.html:

<!DOCTYPE html>
        {% for item in items %}
        <li>{{ }} - {{ item.description }} - ${{ item.price }} - Available: {{ item.available }} - Released: {{ item.release_date }}</li>
        {% endfor %}

Complex Queries and QuerySets

Filtering and Querying

You can perform various queries using Django's ORM:

# Filtering
items = Item.objects.filter(name="Item 1")
# Greater than or equal to
items = Item.objects.filter(price__gte=10)
# Less than or equal to
items = Item.objects.filter(price__lte=50)
# In range
items = Item.objects.filter(price__range=(10, 50))
# Exact match
items = Item.objects.filter(available=True)
# Complex Queries using Q objects
from django.db.models import Q
items = Item.objects.filter(Q(name__startswith='Item') & Q(description__icontains='item'))
# Order by
items = Item.objects.order_by('-created_at')

Serializers and JSON Response

Django REST Framework

Install Django REST Framework:

pip install djangorestframework



Creating a Serializer

Create a serializer in myapp/

from rest_framework import serializers
from .models import Item
class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = '__all__'

Creating an API View

In myapp/, create an API view:

from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Item
from .serializers import ItemSerializer
def api_items(request):
    items = Item.objects.all()
    serializer = ItemSerializer(items, many=True)
    return Response(

Mapping the URL

In myapp/, add the API endpoint:

urlpatterns = [
    path('api/items/', api_items, name='api_items'),

HTML Response

You can return HTML responses using templates, which allows you to dynamically generate HTML pages based on data.

Base Template

Create a base template myapp/templates/base.html:

<!DOCTYPE html>
    <title>{% block title %}My Site{% endblock %}</title>
    {% block content %}{% endblock %}

Extending the Base Template

Create a new template myapp/templates/myapp/new_page.html:

{% extends "base.html" %}
{% block title %}New Page{% endblock %}
{% block content %}
    <h1>Welcome to the New Page</h1>
{% endblock %}

Additional Concepts


Middleware processes requests globally before reaching the view. Create custom middleware in myapp/

class MyMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
    def __call__(self, request):
        response = self.get_response(request)
        return response

Add it to MIDDLEWARE in


Forms and Validation

Create a form in myapp/

from django import forms
from .models import Item
class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ['name', 'description', 'price', 'available', 'release_date', 'image', 'file']

Handle the form in your view:

from .forms import ItemForm
def new_item(request):
    if request.method == 'POST':
        form = ItemForm(request.POST, request.FILES)
        if form.is_valid():
        form = ItemForm()
    return render(request, 'myapp/new_item.html', {'form': form})

Create a template myapp/templates/myapp/new_item.html:

<!DOCTYPE html>
    <title>New Item</title>
    <h1>New Item</h1>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Save</button>

User Authentication

Use Django's built-in authentication views for user login and logout:

from django.contrib.auth import views as auth_views
urlpatterns = [
    path('login/', auth_views.LoginView.as_view(), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),


This comprehensive cheat-sheet provides a detailed guide to getting started with Django and covers essential features such as creating dynamic views, handling forms, working with databases, performing complex queries, and creating APIs using Django REST Framework. With this knowledge, you can build robust and scalable web applications using Django.