Django Cheat Sheet
Project Structure
myproject/
??? [Link]
??? myproject/ # Project settings
? ??? __init__.py
? ??? [Link]
? ??? [Link]
? ??? [Link]
??? myapp/ # Django app
??? [Link]
??? [Link]
??? [Link]
??? [Link]
??? [Link]
??? templates/
??? migrations/
Basic Commands
django-admin startproject myproject
python [Link] startapp myapp
python [Link] runserver
python [Link] makemigrations
python [Link] migrate
python [Link] createsuperuser
python [Link] shell
python [Link] collectstatic
[Link] Configuration
INSTALLED_APPS = [
'[Link]',
'[Link]',
...
'myapp',
'rest_framework',
]
TEMPLATES = [{
'BACKEND': '[Link]',
'DIRS': [BASE_DIR / 'templates'],
...
}]
Models Example
Django Cheat Sheet
from [Link] import models
class Product([Link]):
name = [Link](max_length=100)
price = [Link](max_digits=8, decimal_places=2)
created_at = [Link](auto_now_add=True)
def __str__(self):
return [Link]
Admin Registration
from [Link] import admin
from .models import Product
[Link](Product)
Views and URLs
# [Link]
from [Link] import render
def home(request):
return render(request, '[Link]')
# [Link] in project
from [Link] import path, include
urlpatterns = [
path('admin/', [Link]),
path('', include('[Link]')),
]
# [Link] in app
from [Link] import path
from . import views
urlpatterns = [
path('', [Link], name='home'),
]
Templates
<!-- templates/[Link] -->
<!DOCTYPE html>
<html>
<head><title>Home</title></head>
<body><h1>Hello, Django!</h1></body>
</html>
Django Cheat Sheet
Forms
from django import forms
from .models import Product
class ProductForm([Link]):
class Meta:
model = Product
fields = ['name', 'price']
Django REST Framework
# [Link]
from rest_framework import serializers
from .models import Product
class ProductSerializer([Link]):
class Meta:
model = Product
fields = '__all__'
# [Link]
from rest_framework.views import APIView
from rest_framework.response import Response
class ProductAPI(APIView):
def get(self, request):
products = [Link]()
serializer = ProductSerializer(products, many=True)
return Response([Link])
Authentication Example
from [Link] import authenticate, login
def login_view(request):
user = authenticate(request, username='user', password='pass')
if user is not None:
login(request, user)
QuerySet Examples
[Link]()
[Link](id=1)
[Link](name__icontains='apple')
[Link].order_by('-created_at')