Django
This Django cheatsheet
1. Introduction to Django
-
What is Django?
- Django is a high-level Python web framework that allows rapid development of secure and maintainable websites.
- It follows the MVC (Model-View-Controller) architectural pattern, called MTV (Model-Template-View) in Django.
-
Why Django?
- Rapid development (DRY principle - Don't Repeat Yourself)
- Built-in admin panel
- Secure (prevents SQL injection, XSS, CSRF)
- Scalable and extensible
- Large community and many reusable packages
2. Setting Up Django Environment
Prerequisites
- Python installed (3.8+ recommended)
- Pip package manager
- Virtual environment (recommended to isolate projects)
Step 1: Create Virtual Environment
python -m venv myenv
Step 2: Activate Virtual Environment
- Windows:
myenv\\Scripts\\activate
- Linux/macOS:
source myenv/bin/activate
Step 3: Install Django
pip install django
Step 4: Verify Django Installation
django-admin --version
3. Creating Your First Django Project
Step 1: Start a Project
django-admin startproject myproject
- Creates a folder myproject with structure:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
Step 2: Run Development Server
cd myproject python manage.py runserver
- Open http://127.0.0.1:8000/ to see Django’s default page.
4. Django Project Structure Explained
- manage.py – Command-line utility to interact with your project.
- settings.py – Project configurations: database, apps, templates, static files.
- urls.py – URL routing for the project.
- wsgi.py/asgi.py – Entry point for WSGI/ASGI servers.
- **init.py** – Makes Python treat directory as a package.
5. Creating a Django App
- Django projects are composed of multiple apps.
python manage.py startapp myapp
- Add the app in settings.py:
INSTALLED_APPS = [ ... 'myapp', ]
6. Django URL Routing
- Project URLs (urls.py)
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ]
- App URLs (myapp/urls.py)
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ]
- Views (myapp/views.py)
from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!")
7. Django Views
- Function-Based Views (FBV)
def about(request): return HttpResponse("About Page")
- Class-Based Views (CBV)
from django.views import View from django.http import HttpResponse class AboutView(View): def get(self, request): return HttpResponse("About Page CBV")
8. Templates in Django
- Create template folder inside app:
myapp/templates/myapp/home.html
- Template example:
<!DOCTYPE html> <html> <head> <title>Home</title> </head> <body> <h1>Welcome to Django!</h1> </body> </html>
- Render template in view:
from django.shortcuts import render def home(request): return render(request, 'myapp/home.html')
- Template Context
def home(request): context = {'name': 'Uday'} return render(request, 'myapp/home.html', context)
<h1>Hello, {{ name }}</h1>
9. Static Files and CSS/JS
- Add static folder:
myapp/static/myapp/style.css
- settings.py
STATIC_URL = '/static/'
- Use in template
<link rel="stylesheet" type="text/css" href="{% static 'myapp/style.css' %}" />
- Load static tag
{% load static %}
10. Models and Database
- Django uses ORM (Object Relational Mapping)
- Define Model in models.py
from django.db import models class Student(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() email = models.EmailField() def __str__(self): return self.name
- Migrate Database
python manage.py makemigrations python manage.py migrate
- Interact via Django Shell
python manage.py shell from myapp.models import Student s = Student(name="Uday", age=20, email="uday@example.com") s.save() Student.objects.all()
11. Django Admin
- Create Superuser
python manage.py createsuperuser
- Register Model in admin.py
from django.contrib import admin from .models import Student admin.site.register(Student)
- Access Admin Panel
- URL: http://127.0.0.1:8000/admin/
12. Forms in Django
- Create Form in forms.py
from django import forms from .models import Student class StudentForm(forms.ModelForm): class Meta: model = Student fields = ['name', 'age', 'email']
- View to handle form
def add_student(request): if request.method == 'POST': form = StudentForm(request.POST) if form.is_valid(): form.save() else: form = StudentForm() return render(request, 'myapp/add_student.html', {'form': form})
- Template
<form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form>
13. Django QuerySet & ORM
- Basic Queries
Student.objects.all() Student.objects.filter(age__gt=18) Student.objects.get(id=1) Student.objects.exclude(name="Uday") Student.objects.order_by('name')
- Aggregates
from django.db.models import Avg, Count Student.objects.aggregate(Avg('age')) Student.objects.aggregate(Count('id'))
14. Middleware
- Middleware acts as a bridge between request and response.
- Example: Logging middleware
class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print("Before view") response = self.get_response(request) print("After view") return response
- Add to settings.py under MIDDLEWARE
15. Authentication & Authorization
- Built-in User Model
from django.contrib.auth.models import User
- Login
from django.contrib.auth import authenticate, login user = authenticate(username='uday', password='123') if user: login(request, user)
- Logout
from django.contrib.auth import logout logout(request)
- Decorators
from django.contrib.auth.decorators import login_required @login_required def profile(request): return render(request, 'profile.html')
16. Advanced Topics
a) Class-Based Views (CBV)
- ListView, DetailView, CreateView, UpdateView, DeleteView
b) Django REST Framework (DRF)
- Build RESTful APIs
pip install djangorestframework
- Serializer Example
from rest_framework import serializers from .models import Student class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__'
c) Pagination
- DRF provides pagination for API endpoints
d) Signals
- Execute actions automatically on model events
from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=Student) def student_saved(sender, instance, **kwargs): print("Student saved:", instance.name)
e) Testing
- Django provides built-in test framework using unittest
from django.test import TestCase class StudentTestCase(TestCase): def test_student_creation(self): s = Student.objects.create(name="Test", age=21, email="test@example.com") self.assertEqual(s.name, "Test")
17. Deployment
-
Prepare for Production
- DEBUG = False in settings.py
- Configure ALLOWED_HOSTS
- Use WhiteNoise for static files
- Setup Database (PostgreSQL recommended)
- Use gunicorn/uwsgi + nginx
-
Commands
pip install gunicorn python manage.py collectstatic gunicorn myproject.wsgi
- Deploy Options
- Heroku, AWS EC2, DigitalOcean, PythonAnywhere
18. Extra Features
- Email Integration
- File Uploads
- Signals & Background Tasks (Celery)
- Caching & Performance Optimization
- Internationalization (i18n)