django_cheat_sheet
django_cheat_sheet
Project Structure
myproject/
??? manage.py
??? myproject/ # Project settings
? ??? __init__.py
? ??? settings.py
? ??? urls.py
? ??? wsgi.py
??? myapp/ # Django app
??? admin.py
??? apps.py
??? models.py
??? views.py
??? urls.py
??? templates/
??? migrations/
Basic Commands
settings.py Configuration
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
...
'myapp',
'rest_framework',
]
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
...
}]
Models Example
Django Cheat Sheet
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=8, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
Admin Registration
admin.site.register(Product)
# views.py
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
# urls.py in project
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
# urls.py in app
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
Templates
Forms
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'price']
# serializers.py
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
class ProductAPI(APIView):
def get(self, request):
products = Product.objects.all()
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
Authentication Example
def login_view(request):
user = authenticate(request, username='user', password='pass')
if user is not None:
login(request, user)
QuerySet Examples
Product.objects.all()
Product.objects.get(id=1)
Product.objects.filter(name__icontains='apple')
Product.objects.order_by('-created_at')