Guides
Django Development Guidelines
Provides guidance on Django best practices, models, views, templates, and ORM usage.
Django Development Guidelines
General
- Follow the Django Style Guide and PEP 8.
- Use Django's built-in features whenever possible (authentication, admin, forms).
- Keep applications modular and reusable.
Models (models.py)
- Use descriptive model and field names.
- Define
__str__methods for all models. - Add
Metaoptions for ordering, verbose names, etc. - Use
ForeignKeywithon_deletespecified appropriately (e.g.,models.CASCADE,models.SET_NULL). - Example:
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
Views (views.py)
- Prefer Class-Based Views (CBVs) for common patterns (List, Detail, Create, Update, Delete).
- Use Function-Based Views (FBVs) for simple or highly custom logic.
- Implement proper authentication and permissions (
@login_required,PermissionRequiredMixin). - Handle exceptions gracefully (e.g.,
try...except ObjectDoesNotExist). - Use
get_object_or_404shortcut.
Templates
- Organize templates in app-specific directories (
templates/<app_name>/). - Use template inheritance (
{% extends 'base.html' %}). - Load static files using
{% load static %}and{% static 'path/to/file.css' %}. - Avoid complex logic in templates; use template tags or filters instead.
ORM
- Use queryset filtering (
.filter(),.exclude()) efficiently. Avoid loading unnecessary data. - Utilize
select_related(for one-to-one/foreign key) andprefetch_related(for many-to-many/reverse foreign key) to optimize database queries. - Use
.annotate()for database-level aggregations. - Be mindful of lazy loading and potential N+1 query problems.
Forms (forms.py)
- Use Django Forms for data validation and HTML generation.
- Prefer
ModelFormfor forms tied directly to models. - Define custom validation methods (
clean_<fieldname>(),clean()).
URLs (urls.py)
- Use descriptive URL names (
path('articles/<int:pk>/', views.ArticleDetailView.as_view(), name='article-detail')). - Include app-specific
urls.pyfiles usinginclude().
Settings (settings.py)
- Use environment variables for sensitive data (SECRET_KEY, database credentials). Do not commit secrets.
- Configure
STATIC_URL,STATIC_ROOT,MEDIA_URL,MEDIA_ROOTcorrectly.
Testing
- Write unit tests and integration tests using Django's
TestCaseorpytest-django. - Test models, views, forms, and utilities.