logo
eng-flag

Django Cheatsheet

Table of Contents

  1. Installation and Setup
  2. Project Structure
  3. Models
  4. Views
  5. URLs
  6. Templates
  7. Forms
  8. Admin Interface
  9. Database Operations
  10. Authentication
  11. Static Files
  12. Testing
  13. Deployment

Installation and Setup

Install Django

pip install django

Create a new Django project

django-admin startproject myproject
cd myproject

Create a new app

python manage.py startapp myapp

Run development server

python manage.py runserver

Create database tables

python manage.py migrate

Project Structure

  • manage.py: Command-line utility for administrative tasks
  • myproject/: Project directory
    • __init__.py: Empty file that tells Python this directory is a package
    • settings.py: Project settings/configuration
    • urls.py: Project URL declarations
    • asgi.py: Entry-point for ASGI-compatible web servers
    • wsgi.py: Entry-point for WSGI-compatible web servers
  • myapp/: Application directory
    • migrations/: Database migrations
    • __init__.py: Empty file that tells Python this directory is a package
    • admin.py: Admin interface configuration
    • apps.py: App configuration
    • models.py: Data models
    • tests.py: Unit tests
    • views.py: View functions

Models

Define a model

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    birth_date = models.DateField()
    
    def __str__(self):
        return f"{self.first_name} {self.last_name}"

Create and save an instance

person = Person(first_name="John", last_name="Doe", birth_date="1990-01-01")
person.save()

Query the database

# Get all persons
all_persons = Person.objects.all()

# Filter persons
johns = Person.objects.filter(first_name="John")

# Get a single person
try:
    person = Person.objects.get(id=1)
except Person.DoesNotExist:
    print("Person not found")

Views

Function-based view

from django.shortcuts import render
from django.http import HttpResponse

def hello_world(request):
    return HttpResponse("Hello, World!")

def person_detail(request, person_id):
    person = Person.objects.get(id=person_id)
    return render(request, 'person_detail.html', {'person': person})

Class-based view

from django.views import View
from django.views.generic import ListView, DetailView

class PersonList(ListView):
    model = Person
    template_name = 'person_list.html'
    context_object_name = 'persons'

class PersonDetail(DetailView):
    model = Person
    template_name = 'person_detail.html'
    context_object_name = 'person'

URLs

URL configuration (urls.py)

from django.urls import path
from . import views

urlpatterns = [
    path('', views.hello_world, name='hello_world'),
    path('person/<int:person_id>/', views.person_detail, name='person_detail'),
    path('persons/', views.PersonList.as_view(), name='person_list'),
    path('person/<int:pk>/', views.PersonDetail.as_view(), name='person_detail'),
]

Templates

Basic template (person_detail.html)

<!DOCTYPE html>
<html>
<head>
    <title>{{ person.first_name }} {{ person.last_name }}</title>
</head>
<body>
    <h1>{{ person.first_name }} {{ person.last_name }}</h1>
    <p>Birth Date: {{ person.birth_date }}</p>
</body>
</html>

Template with inheritance

<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
    {% block content %}
    {% endblock %}
</body>
</html>

<!-- person_detail.html -->
{% extends "base.html" %}

{% block title %}{{ person.first_name }} {{ person.last_name }}{% endblock %}

{% block content %}
    <h1>{{ person.first_name }} {{ person.last_name }}</h1>
    <p>Birth Date: {{ person.birth_date }}</p>
{% endblock %}

Forms

ModelForm

from django import forms
from .models import Person

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ['first_name', 'last_name', 'birth_date']

Using a form in a view

from django.shortcuts import render, redirect
from .forms import PersonForm

def create_person(request):
    if request.method == 'POST':
        form = PersonForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('person_list')
    else:
        form = PersonForm()
    return render(request, 'create_person.html', {'form': form})

Admin Interface

Register a model with the admin site

from django.contrib import admin
from .models import Person

admin.site.register(Person)

Customizing the admin interface

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'birth_date')
    list_filter = ('birth_date',)
    search_fields = ('first_name', 'last_name')

Database Operations

Create migrations

python manage.py makemigrations

Apply migrations

python manage.py migrate

Raw SQL queries

from django.db import connection

def my_custom_sql():
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM myapp_person WHERE birth_date > %s", [date(1990, 1, 1)])
        row = cursor.fetchone()
    return row

Authentication

User login view

from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect

def user_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('home')
        else:
            return render(request, 'login.html', {'error': 'Invalid credentials'})
    return render(request, 'login.html')

Logout view

from django.contrib.auth import logout
from django.shortcuts import redirect

def user_logout(request):
    logout(request)
    return redirect('home')

Login required decorator

from django.contrib.auth.decorators import login_required

@login_required
def protected_view(request):
    return render(request, 'protected.html')

Static Files

Settings for static files

# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR / "static",
]

Using static files in templates

{% load static %}
<img src="{% static 'images/logo.png' %}" alt="Logo">
<link rel="stylesheet" href="{% static 'css/style.css' %}">

Testing

Writing a test

from django.test import TestCase
from .models import Person

class PersonModelTest(TestCase):
    def setUp(self):
        Person.objects.create(first_name="John", last_name="Doe", birth_date="1990-01-01")

    def test_person_creation(self):
        person = Person.objects.get(first_name="John")
        self.assertEqual(person.last_name, "Doe")

Running tests

python manage.py test

Deployment

Settings for production

# settings.py
DEBUG = False
ALLOWED_HOSTS = ['www.example.com']

# Security settings
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

Collecting static files

python manage.py collectstatic

Using a production-ready web server (e.g., Gunicorn)

gunicorn myproject.wsgi:application

2024 © All rights reserved - buraxta.com