Django Cheat-Sheet: From Scratch to Advanced Features.

Jagrit Thapar

1058 words • 6 min read

Introduction

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 manage.py runserver

You can access the development server at http://127.0.0.1:8000/.

Creating and Adding an App

Creating a New App

Create a new app within your project:

python manage.py startapp myapp

Registering the App

Add your new app to the INSTALLED_APPS list in myproject/settings.py:

INSTALLED_APPS = [
    ...
    'myapp',
]

Creating Static Views

Basic View

Create a simple view in myapp/views.py:

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

Mapping the URL

Map the URL to your view in myapp/urls.py:

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

Ensure myapp/urls.py is included in the project’s urls.py:

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

Creating Dynamic Views

Template Rendering

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

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>

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/settings.py:

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

Creating Models with Various Field Types

In myapp/models.py, 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):
        return self.name

Making Migrations

Create and apply migrations:

python manage.py makemigrations
python manage.py migrate

Django ORM and Data Fetching

Adding Data

You can add data using the Django admin or shell:

python manage.py 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/views.py, 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>
<html>
<head>
    <title>Items</title>
</head>
<body>
    <h1>Items</h1>
    <ul>
        {% for item in items %}
        <li>{{ item.name }} - {{ item.description }} - ${{ item.price }} - Available: {{ item.available }} - Released: {{ item.release_date }}</li>
        {% endfor %}
    </ul>
</body>
</html>

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

Add it to INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'rest_framework',
]

Creating a Serializer

Create a serializer in myapp/serializers.py:

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/views.py, 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
 
@api_view(['GET'])
def api_items(request):
    items = Item.objects.all()
    serializer = ItemSerializer(items, many=True)
    return Response(serializer.data)

Mapping the URL

In myapp/urls.py, 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>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

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

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

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 settings.py:

MIDDLEWARE = [
    ...
    'myapp.middleware.MyMiddleware',
]

Forms and Validation

Create a form in myapp/forms.py:

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.save()
    else:
        form = ItemForm()
    return render(request, 'myapp/new_item.html', {'form': form})

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

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

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'),
]

Conclusion

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.