<< All versions
Skill v1.0.0
currentAutomated scan100/100hiddink-ai/hiddink-harness/django-best-practices
──Details
PublishedNovember 22, 2026 at 08:17 PM
Content Hashsha256:e7c5e1b9690f1556...
Git SHAeadcfae57dc6
──Files
Files (1 file, 9.4 KB)
SKILL.md9.4 KBactive
SKILL.md · 337 lines · 9.4 KB
name: django-best-practices description: Django patterns for production-ready Python web applications scope: core user-invocable: false metadata: version: "1.0.0"
Purpose
Apply Django 6.0.4 patterns for building production-ready, secure, and maintainable Python web applications.
Rules
1. Project Structure
yaml
structure:settings_split: truelayout: "config/{settings/{base,development,production}.py,urls.py,wsgi.py} + apps/{core/,users/,<feature>/} + templates/ + static/ + requirements/{base,development,production}.txt"app_module_contents:models.py: Database modelsviews.py: Request handlersurls.py: URL patterns (with app_name)serializers.py: DRF serializers (if API)forms.py: Django formsadmin.py: Admin customizationservices.py: Business logic layermanagers.py: Custom model managerssignals.py: Django signals (use sparingly)tests/: Test suite (mirror app structure)
Reference: guides/django-best-practices/README.md
2. Models Best Practices
yaml
custom_user_model:rule: ALWAYS create a custom User model, even if identical to defaultlocation: apps/users/models.pyreason: Impossible to swap default User model mid-projectpattern: "Extend AbstractUser, set AUTH_USER_MODEL in settings"primary_key:default: BigAutoFieldsettings: DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'model_meta:required:- __str__: human-readable representation- Meta.ordering: consistent default ordering- Meta.verbose_name: singular display name- Meta.verbose_name_plural: plural display namequery_optimization:foreign_key: select_related() # Single SQL JOINmany_to_many: prefetch_related() # Separate query + Python joinpartial_fields: only() / defer() # Load subset of fieldsaggregations: F() and Q() objects for complex expressionsbulk_ops:create: bulk_create(objs, batch_size=1000)update: bulk_update(objs, fields, batch_size=1000)indexing:- Frequently filtered fields: db_index=True- Frequently ordered fields: Meta.ordering fields- Multi-column: Meta.indexes with models.Index- Unique together: Meta.unique_together or UniqueConstraintconstraints:use: Meta.constraints for database-level enforcementtypes: "UniqueConstraint, CheckConstraint"soft_delete:pattern: is_active = models.BooleanField(default=True)manager: Override default manager to filter is_active=Truecustom_managers:rule: Use managers for reusable querysets
Reference: guides/django-best-practices/README.md
3. Views Best Practices
yaml
cbv_vs_fbv:cbv: Standard CRUD, predictable patterns (ListView, DetailView, etc.)fbv: Complex custom logic, non-standard workflowsthin_views:rule: Keep views thin — delegate business logic to services/modelsshortcuts:- get_object_or_404(Model, pk=pk): Returns 404 instead of 500- get_list_or_404(Model, **kwargs): 404 if empty listmixins:authentication: LoginRequiredMixinpermissions: PermissionRequiredMixinuser_pass: UserPassesTestMixinstatus_codes:200: OK (default for success)201: Created (after successful creation)302: Redirect (after POST success — PRG pattern)400: Bad Request (validation error)403: Forbidden (permission denied)404: Not Found405: Method Not Allowed
4. URL Patterns
yaml
namespacing:app_name: Required in every app's urls.pyusage: "reverse('app_name:url_name') or {% url 'app_name:url_name' %}"syntax:prefer: path() over re_path() for clarityuse_re_path: Only for complex regex patternsnaming:rule: Name ALL URL patternsconvention: "{resource}-{action} (e.g., article-list, article-detail)"inclusion:root_urls: Use include() for app-level URLs
Reference: guides/django-best-practices/README.md
5. Forms & Validation
yaml
model_forms:rule: Use ModelForm when form maps to a modelfields: "Explicitly list fields (never use fields = '__all__')"validation:field_level: clean_<field>() methodcross_field: clean() methodbuilt_in: Use Django validators (MaxValueValidator, RegexValidator, etc.)
Reference: guides/django-best-practices/README.md
6. Security
yaml
environment:SECRET_KEY: Never hardcode — read from environment variableDEBUG: False in production (MUST)ALLOWED_HOSTS: Explicitly set in production (MUST)https:SECURE_SSL_REDIRECT: trueSESSION_COOKIE_SECURE: trueCSRF_COOKIE_SECURE: trueSECURE_HSTS_SECONDS: 3600 # Start small, increase to 31536000SECURE_HSTS_INCLUDE_SUBDOMAINS: trueclickjacking:X_FRAME_OPTIONS: DENYcontent_type:SECURE_CONTENT_TYPE_NOSNIFF: truecsrf:rule: Enabled by default via CsrfViewMiddleware — do NOT disablesql_injection:rule: Use ORM, avoid raw SQL; if needed, use parameterized queriesxss:rule: Templates auto-escape by default — never use |safe with user contentdeployment_check:command: python manage.py check --deployrun: Before every production deployment
7. Testing
yaml
framework:preferred: pytest-django (over unittest)config: pytest.ini or pyproject.toml with [tool.pytest.ini_options]test_classes:database: TestCase (wraps each test in transaction)no_database: SimpleTestCase (faster)live_server: LiveServerTestCase (for Selenium)test_data:preferred: factory_boy or model_bakeryavoid: fixtures (hard to maintain, slow)request_testing:Client: Full request/response cycle (preferred for views)RequestFactory: Faster, no middleware (for unit testing views)settings_override:decorator: '@override_settings(...)'coverage:target: 80%+exclude: migrations, admin, settingsstructure:mirror_app: tests/test_models.py, tests/test_views.py, tests/test_forms.py
Reference: guides/django-best-practices/README.md
8. Performance
yaml
n_plus_1_prevention:check: Use django-debug-toolbar in developmentfix_fk: select_related('author', 'category')fix_m2m: prefetch_related('tags', 'comments')complex: Prefetch object with custom querysetpartial_loading:only: "only('id', 'title', 'created_at') — Load only these fields"defer: "defer('body', 'metadata') — Load all except these"values: "values('id', 'title') — Returns dicts (no ORM overhead)"values_list: "values_list('id', flat=True) — Returns flat list"caching:backend: Redis (preferred), Memcachedview_cache: "'@cache_page(60 * 15)' decorator"template_cache: "'{% cache 500 sidebar %}' template tag"low_level: cache.get/set/delete for fine-grained controlpagination:list_views: Always paginate large querysetspage_size: Set reasonable default (20-50 items)drf: PageNumberPagination or CursorPaginationbulk_operations:create: "bulk_create(articles, batch_size=1000)"update: "bulk_update(articles, ['status'], batch_size=1000)"avoid: Loops calling .save() on many objects
9. Django REST Framework (DRF)
yaml
serializers:standard_crud: ModelSerializerread_only: Use SerializerMethodField for computed valueswrite_validation: validate_<field>() and validate() methodsviewsets:standard: ModelViewSet for full CRUDcustom: ViewSet with explicit action methodsrouters: DefaultRouter or SimpleRouter for URL generationauthentication:jwt: djangorestframework-simplejwt (recommended)token: DRF built-in TokenAuthenticationsession: SessionAuthentication (for browser clients)permissions:global: DEFAULT_PERMISSION_CLASSES in settingsper_view: permission_classes attribute on ViewSetobject_level: has_object_permission() in custom permission classversioning:method: NamespaceVersioning or URLPathVersioningthrottling:anonymous: AnonRateThrottleauthenticated: UserRateThrottlecustom: Extend BaseThrottlepagination:global: DEFAULT_PAGINATION_CLASS in settingstypes: PageNumberPagination (simple), CursorPagination (large datasets)
Reference: guides/django-best-practices/README.md
10. Deployment
yaml
wsgi_asgi:wsgi: gunicorn (4 workers per CPU core)asgi: uvicorn with gunicorn workers (for async/WebSocket)static_files:development: Django's staticfilesproduction: whitenoise middleware OR CDN (S3 + CloudFront)command: python manage.py collectstatic --noinputdatabase:development: SQLite (acceptable)production: PostgreSQL (MUST — never SQLite in production)connection_pooling: Use pgBouncer or django-db-connection-poolmigrations:deploy: Run as part of CI/CD pipeline before server restartzero_downtime: Use additive migrations (add nullable columns, backfill, then add constraint)logging:config: LOGGING dict in settingshandler: File handler in production, console in developmentlevel: WARNING in production, DEBUG in developmentenvironment_variables:tool: python-decouple or django-environnever: Hardcode secrets in settings fileshealth_check:endpoint: /health/ returning 200 OKchecks: Database connection, cache connection, disk space
Application
When writing Django code:
- Always create a custom User model before any other models
- Always split settings into base/development/production
- Prefer CBVs for standard CRUD, FBVs for custom logic
- Use select_related/prefetch_related to prevent N+1 queries
- Apply the security checklist for every production deployment
- Test with pytest-django and factory_boy
- Never use
fields = '__all__'in ModelForms or ModelSerializer - Run
python manage.py check --deploybefore shipping