django Best Practices
This guide outlines the definitive best practices for developing Django applications, ensuring maintainability, performance, and security. Adhere to these rules for consistent, high-quality code.
1. Code Organization & Project Structure
Adopt the src-layout for clear separation of concerns. Keep apps focused on a single domain.
Project Layout (src-layout):
.
├── manage.py
├── src/
│ ├── config/ # Project-level settings, URLs, WSGI/ASGI
│ │ ├── __init__.py
│ │ ├── settings/
│ │ │ ├── __init__.py
│ │ │ ├── base.py
│ │ │ ├── development.py
│ │ │ └── production.py
│ │ └── urls.py
│ ├── apps/ # Domain-driven Django apps
│ │ ├── users/
│ │ │ ├── models.py
│ │ │ ├── views.py
│ │ │ └── tests/
│ │ ├── products/
│ │ └── ...
│ └── common/ # Reusable utilities, abstract base models, etc.
└── requirements.txt
Split Settings: Use django-environ for environment-specific settings. Never commit secrets.
❌ BAD: Hardcoding secrets, single settings.py
# config/settings.py
DEBUG = True
SECRET_KEY = 'super-secret-dev-key'
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3'}}
✅ GOOD: Environment variables, split files
# src/config/settings/base.py
import environ
env = environ.Env()
environ.Env.read_env() # reads .env file
SECRET_KEY = env('SECRET_KEY')
DEBUG = env.bool('DEBUG', default=False)
ALLOWED_HOSTS = env.list('ALLOWED_HOSTS', default=[])
# src/config/settings/development.py
from .base import *
DEBUG = True
DATABASES = {'default': env.db('DATABASE_URL', default='sqlite:///db.sqlite3')}
# .env file (not committed to VCS)
SECRET_KEY=your_actual_secret_key
DEBUG=True
DATABASE_URL=postgres://user:pass@host:port/dbname
Model Naming: Models are singular nouns. related_name for reverse relationships is plural.
❌ BAD:
class Users(models.Model): pass
owner = models.ForeignKey(Owner, related_name='item')
✅ GOOD:
class User(models.Model): pass
owner = models.ForeignKey(Owner, related_name='items',
2. Common Patterns & Anti-patterns
Fat Models, Skinny Views: Business logic belongs in models or dedicated service layers, not views. Views orchestrate, models/services execute.
❌ BAD: Logic in view
# apps/orders/views.py
def create_order_view(request):
# ... validation ...
product = Product.objects.get(id=product_id)
if product.stock < quantity:
raise ValidationError("Not enough stock")
order = Order.objects.create(user=request.user, product=product, quantity=quantity)
product.stock -= quantity
product.save()
# ...
✅ GOOD: Logic in model/service
# apps/orders/models.py
class Order(models.Model):
# ... fields ...
@classmethod
def create_with_stock_check(cls, user, product, quantity):
if product.stock < quantity:
raise ValidationError("Not enough stock")
order = cls.objects.create(user=user, product=product, quantity=quantity)
product.stock -= quantity
product.save()
return order
# apps/orders/views.py
def create_order_view(request):
# ... validation ...
order = Order.create_with_stock_check(request.user, product, quantity)
# ...
3. Performance Considerations
Optimize ORM Queries: Avoid N+1 queries.
❌ BAD: N+1 query
# Iterates over users, then queries profile for each
users = User.objects.all()
for user in users:
print(user.profile.bio)
✅ GOOD: select_related (one-to-one, foreign key)
users = User.objects.select_related('profile').all()
for user in users:
print(user.profile.bio)
✅ GOOD: prefetch_related (many-to-many, reverse foreign key)
# For a list of books, prefetch all authors for each book
books = Book.objects.prefetch_related('authors').all()
for book in books:
print([author.name for author in book.authors.all()])
Database Indexes: Add db_index=True to frequently filtered/ordered fields.
class MyModel(models.Model):
name = models.CharField(max_length=100, db_index=True) # Indexed
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
Async ORM: Use sync_to_async for blocking ORM calls in async views, or the native async ORM (Django 4.1+).
# In an async view
from asgiref.sync import sync_to_async
async def my_async_view(request):
# Blocking ORM call, wrap it
user = await sync_to_async(User.objects.get)(id=request.user.id)
# Or, if using native async ORM (Django 4.1+):
# user = await User.objects.aget(id=request.user.id)
return JsonResponse({'username': user.username})
4. Security Best Practices
Secrets Management: Never commit secrets to VCS. Use environment variables (see Split Settings).
Permissions (DRF): Implement role-based permissions using DRF's permission_classes.
❌ BAD: Manual checks in view
class MyView(APIView):
def get(self, request):
if not request.user.is_staff:
return Response(status=403)
# ...
✅ GOOD: DRF Permission Classes
from rest_framework.permissions import IsAdminUser
class MyView(APIView):
permission_classes = [IsAdminUser] # Only staff can access
def get(self, request):
# ...
Static & Media Files: Serve static files with ManifestStaticFilesStorage and media files from cloud storage (e.g., S3, GCS).
# config/settings/production.py
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # e.g., django-storages
5. API Design (DRF)
ViewSets & Routers: Use ModelViewSet for CRUD operations to reduce boilerplate.
❌ BAD: Separate views for list and detail
class ProductListView(APIView): pass
class ProductDetailView(APIView): pass
# urls.py: path('products/', ProductListView.as_view()), path('products/<int:pk>/', ProductDetailView.as_view())
✅ GOOD: ModelViewSet with Router
# apps/products/views.py
from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
# src/config/urls.py
from rest_framework.routers import DefaultRouter
from apps.products.views import ProductViewSet
router = DefaultRouter()
router.register(r'products', ProductViewSet)
urlpatterns = [
# ...
path('api/', include(router.urls)),
]
6. Type Hints
Always use type hints for improved readability, maintainability, and static analysis with mypy.
❌ BAD: Untyped function
def calculate_total(price, quantity):
return price * quantity
✅ GOOD: Typed function
def calculate_total(price: float, quantity: int) -> float:
return price * quantity
# For models:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from django.db.models import QuerySet
class Product(models.Model):
name: str = models.CharField(max_length=255)
price: float = models.DecimalField(max_digits=10, decimal_places=2)
def get_related_products(self) -> "QuerySet[Product]":
# ...
return Product.objects.filter(...)
1---2name: django3description: [Applies to: **/*.py] Definitive guidelines for writing maintainable, performant, and secure Django applications, emphasizing modern best practices, clear code organization, and efficient patterns.4---56# django Best Practices78This guide outlines the definitive best practices for developing Django applications, ensuring maintainability, performance, and security. Adhere to these rules for consistent, high-quality code.910## 1. Code Organization & Project Structure1112Adopt the `src-layout` for clear separation of concerns. Keep apps focused on a single domain.1314* **Project Layout (`src-layout`)**:15 ```16 .17 ├── manage.py18 ├── src/19 │ ├── config/ # Project-level settings, URLs, WSGI/ASGI20 │ │ ├── __init__.py21 │ │ ├── settings/22 │ │ │ ├── __init__.py23 │ │ │ ├── base.py24 │ │ │ ├── development.py25 │ │ │ └── production.py26 │ │ └── urls.py27 │ ├── apps/ # Domain-driven Django apps28 │ │ ├── users/29 │ │ │ ├── models.py30 │ │ │ ├── views.py31 │ │ │ └── tests/32 │ │ ├── products/33 │ │ └── ...34 │ └── common/ # Reusable utilities, abstract base models, etc.35 └── requirements.txt36 ```3738* **Split Settings**: Use `django-environ` for environment-specific settings. Never commit secrets.3940 ❌ BAD: Hardcoding secrets, single `settings.py`41 ```python42 # config/settings.py43 DEBUG = True44 SECRET_KEY = 'super-secret-dev-key'45 DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3'}}46 ```4748 ✅ GOOD: Environment variables, split files49 ```python50 # src/config/settings/base.py51 import environ52 env = environ.Env()53 environ.Env.read_env() # reads .env file5455 SECRET_KEY = env('SECRET_KEY')56 DEBUG = env.bool('DEBUG', default=False)57 ALLOWED_HOSTS = env.list('ALLOWED_HOSTS', default=[])5859 # src/config/settings/development.py60 from .base import *61 DEBUG = True62 DATABASES = {'default': env.db('DATABASE_URL', default='sqlite:///db.sqlite3')}6364 # .env file (not committed to VCS)65 SECRET_KEY=your_actual_secret_key66 DEBUG=True67 DATABASE_URL=postgres://user:pass@host:port/dbname68 ```6970* **Model Naming**: Models are singular nouns. `related_name` for reverse relationships is plural.7172 ❌ BAD:73 ```python74 class Users(models.Model): pass75 owner = models.ForeignKey(Owner, related_name='item')76 ```7778 ✅ GOOD:79 ```python80 class User(models.Model): pass81 owner = models.ForeignKey(Owner, related_name='items', on_delete=models.CASCADE)82 ```8384## 2. Common Patterns & Anti-patterns8586* **Fat Models, Skinny Views**: Business logic belongs in models or dedicated service layers, not views. Views orchestrate, models/services execute.8788 ❌ BAD: Logic in view89 ```python90 # apps/orders/views.py91 def create_order_view(request):92 # ... validation ...93 product = Product.objects.get(id=product_id)94 if product.stock < quantity:95 raise ValidationError("Not enough stock")96 order = Order.objects.create(user=request.user, product=product, quantity=quantity)97 product.stock -= quantity98 product.save()99 # ...100 ```101102 ✅ GOOD: Logic in model/service103 ```python104 # apps/orders/models.py105 class Order(models.Model):106 # ... fields ...107 @classmethod108 def create_with_stock_check(cls, user, product, quantity):109 if product.stock < quantity:110 raise ValidationError("Not enough stock")111 order = cls.objects.create(user=user, product=product, quantity=quantity)112 product.stock -= quantity113 product.save()114 return order115116 # apps/orders/views.py117 def create_order_view(request):118 # ... validation ...119 order = Order.create_with_stock_check(request.user, product, quantity)120 # ...121 ```122123## 3. Performance Considerations124125* **Optimize ORM Queries**: Avoid N+1 queries.126127 ❌ BAD: N+1 query128 ```python129 # Iterates over users, then queries profile for each130 users = User.objects.all()131 for user in users:132 print(user.profile.bio)133 ```134135 ✅ GOOD: `select_related` (one-to-one, foreign key)136 ```python137 users = User.objects.select_related('profile').all()138 for user in users:139 print(user.profile.bio)140 ```141142 ✅ GOOD: `prefetch_related` (many-to-many, reverse foreign key)143 ```python144 # For a list of books, prefetch all authors for each book145 books = Book.objects.prefetch_related('authors').all()146 for book in books:147 print([author.name for author in book.authors.all()])148 ```149150* **Database Indexes**: Add `db_index=True` to frequently filtered/ordered fields.151 ```python152 class MyModel(models.Model):153 name = models.CharField(max_length=100, db_index=True) # Indexed154 created_at = models.DateTimeField(auto_now_add=True, db_index=True)155 ```156157* **Async ORM**: Use `sync_to_async` for blocking ORM calls in async views, or the native async ORM (Django 4.1+).158159 ```python160 # In an async view161 from asgiref.sync import sync_to_async162163 async def my_async_view(request):164 # Blocking ORM call, wrap it165 user = await sync_to_async(User.objects.get)(id=request.user.id)166 # Or, if using native async ORM (Django 4.1+):167 # user = await User.objects.aget(id=request.user.id)168 return JsonResponse({'username': user.username})169 ```170171## 4. Security Best Practices172173* **Secrets Management**: Never commit secrets to VCS. Use environment variables (see Split Settings).174175* **Permissions (DRF)**: Implement role-based permissions using DRF's `permission_classes`.176177 ❌ BAD: Manual checks in view178 ```python179 class MyView(APIView):180 def get(self, request):181 if not request.user.is_staff:182 return Response(status=403)183 # ...184 ```185186 ✅ GOOD: DRF Permission Classes187 ```python188 from rest_framework.permissions import IsAdminUser189190 class MyView(APIView):191 permission_classes = [IsAdminUser] # Only staff can access192 def get(self, request):193 # ...194 ```195196* **Static & Media Files**: Serve static files with `ManifestStaticFilesStorage` and media files from cloud storage (e.g., S3, GCS).197198 ```python199 # config/settings/production.py200 STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'201 DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # e.g., django-storages202 ```203204## 5. API Design (DRF)205206* **ViewSets & Routers**: Use `ModelViewSet` for CRUD operations to reduce boilerplate.207208 ❌ BAD: Separate views for list and detail209 ```python210 class ProductListView(APIView): pass211 class ProductDetailView(APIView): pass212 # urls.py: path('products/', ProductListView.as_view()), path('products/<int:pk>/', ProductDetailView.as_view())213 ```214215 ✅ GOOD: `ModelViewSet` with Router216 ```python217 # apps/products/views.py218 from rest_framework import viewsets219 from .models import Product220 from .serializers import ProductSerializer221222 class ProductViewSet(viewsets.ModelViewSet):223 queryset = Product.objects.all()224 serializer_class = ProductSerializer225226 # src/config/urls.py227 from rest_framework.routers import DefaultRouter228 from apps.products.views import ProductViewSet229230 router = DefaultRouter()231 router.register(r'products', ProductViewSet)232 urlpatterns = [233 # ...234 path('api/', include(router.urls)),235 ]236 ```237238## 6. Type Hints239240Always use type hints for improved readability, maintainability, and static analysis with `mypy`.241242❌ BAD: Untyped function243```python244def calculate_total(price, quantity):245 return price * quantity246```247248✅ GOOD: Typed function249```python250def calculate_total(price: float, quantity: int) -> float:251 return price * quantity252253# For models:254from typing import TYPE_CHECKING255if TYPE_CHECKING:256 from django.db.models import QuerySet257258class Product(models.Model):259 name: str = models.CharField(max_length=255)260 price: float = models.DecimalField(max_digits=10, decimal_places=2)261262 def get_related_products(self) -> "QuerySet[Product]":263 # ...264 return Product.objects.filter(...)265```