Token导航 LogoToken导航TokenDH.com
开发规范敏感数据github未标认证来源可访问许可证需确认审计通过

django-best-practicesDjango 最佳实践

Agent Skill

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流。它适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令、生成脚本或分析数据处理逻辑。使用时需要确认项目虚拟环境、依赖版本和测试入口;涉及执行脚本、读写文件、访问数据库或调用外部 API 时,应先明确运行目录和输入输出范围,避免误改生产数据。

总安装

346

周安装

14

GitHub Stars

4

下载量

109
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:django-best-practices(Django 最佳实践)
来源仓库:https://github.com/reyretee/django-skills
仓库路径:skills/django-best-practices
安装命令:
npx skills add https://github.com/reyretee/django-skills --skill django-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/reyretee/django-skills --skill django-best-practices

简介

提供 Django 开发最佳实践知识库,覆盖 27 个核心主题。

  • 包含 ORM 查询优化、安全配置、部署策略和架构设计指导。
  • 通过错误示例与正确实现对比,提升代码质量和可维护性。
  • 安装方式:github,通过 npx skills add 命令添加。
  • 适用于代码审查、新项目开发和技术培训场景。django-best-practices 属于开发规范类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Django Best Practices

A senior Django developer's knowledge base covering 27 topics — from ORM queries to deployment. This skill provides wrong vs correct code examples and architectural guidance for building production-grade Django applications.

When to use this skill

  • Creating or modifying Django models, fields, or relations
  • Writing views (FBV, CBV, or DRF ViewSets)
  • Building or updating DRF serializers and API endpoints
  • Writing ORM queries, fixing N+1 problems, or optimizing performance
  • Creating or reviewing migrations
  • Configuring Django settings, middleware, or URL routing
  • Implementing authentication, permissions, or session management
  • Setting up caching (Redis, Memcached, per-view, fragment)
  • Writing or reviewing tests (Django TestCase, pytest, factories)
  • Working with Django signals, forms, templates, or template tags
  • Configuring static/media files, file uploads, or storage backends
  • Setting up Celery tasks, periodic tasks, or background jobs
  • Deploying Django (Gunicorn, Nginx, Docker, CI/CD)
  • Working with Django Channels or WebSockets
  • Implementing i18n/l10n or timezone support
  • Reviewing code for security issues (CSRF, XSS, SQL injection)
  • Designing app architecture, service layers, or project structure

Workflow

When this skill is activated, follow these steps:

  1. Identify the topic — Determine which area of Django the task involves (models, views, queries, etc.)
  2. Read the relevant reference file — Consult the reference table below and read the appropriate file before writing any code
  3. Apply the correct patterns — Follow the "Correct" patterns from the reference file, avoid the "Wrong" anti-patterns
  4. Check for common mistakes — Review the "Why" explanations to understand the reasoning behind each pattern
  5. Cross-reference related topics — If the task spans multiple areas (e.g., views + queries + templates), read all relevant reference files
Always read the relevant reference file before writing code for that topic.

Key Principles

Project Structure

  • Separate config from apps. Use config/settings/ with base, local, and production files.
  • Keep apps small and focused (3-8 models per app). Split when an app exceeds 15 models.
  • Always set AUTH_USER_MODEL before the first migration.
  • Reference users via settings.AUTH_USER_MODEL, never auth.User directly.

Models & ORM

  • Use DecimalField for money, BooleanField for flags, EmailField for emails.
  • Always set explicit related_name on ForeignKey and OneToOneField.
  • Use select_related for ForeignKey/OneToOne, prefetch_related for ManyToMany/reverse FK.
  • Use F() expressions for atomic updates to avoid race conditions.
  • Use Exists() instead of .count() > 0 for existence checks.
  • Use bulk_create and bulk_update for batch operations.
  • Wrap multi-step writes in transaction.atomic().

Queries

  • Never filter in Python when the database can do it.
  • Use Q objects for OR/NOT queries.
  • Use annotate with Subquery instead of N+1 loops.
  • Always parameterize raw SQL — never use f-strings.
  • Use .values_list() when you don't need full model instances.
  • Use .exists() instead of .count() > 0.
  • Use .iterator() for large querysets.

Views

  • Use FBVs for simple one-off views, CBVs for CRUD with generics.
  • Always use LoginRequiredMixin or @login_required for protected views.
  • Override get_queryset() to enforce ownership in UpdateView/DeleteView.
  • Use get_object_or_404 in views, .first() when absence is expected.

Forms & Validation

  • Always use explicit fields in ModelForm — never exclude or __all__.
  • Use clean_<field>() for single-field validation, clean() for cross-field.
  • Use Django's built-in validators and write custom ones for domain rules.

Security

  • Never disable CSRF except for external webhooks with their own auth.
  • Never use mark_safe() or |safe on user input — use format_html().
  • Never use f-strings in raw SQL — always parameterize.
  • Use Argon2 for password hashing, PBKDF2 as fallback.
  • Set SECURE_SSL_REDIRECT, SECURE_HSTS_*, and cookie security flags in production.
  • Run manage.py check --deploy before every deployment.

Admin

  • Always configure list_display, list_filter, and search_fields.
  • Use list_select_related to prevent N+1 queries in list views.
  • Use readonly_fields for computed/automatic values.
  • Override permission methods to restrict what staff can do.

Templates

  • Use template inheritance with base.html and {% block %} tags.
  • Always use {% url %} and {% static %} — never hardcode paths.
  • Use {% empty %} in for loops and {% with %} for expensive lookups.
  • Never use {% autoescape off %} or |safe on user content.

Migrations

  • Make small, focused migrations with descriptive names.
  • Always provide reverse operations for custom/data migrations.
  • Use apps.get_model() in data migrations, never direct model imports.
  • Multi-step approach for column removal: make nullable → deploy → remove.
  • Use --plan to preview migrations before running in production.

Testing

  • Use SimpleTestCase for no-DB tests, TestCase for DB tests.
  • Use setUpTestData for class-level test data (faster than setUp).
  • Use factory_boy instead of JSON fixtures.
  • Mock external services (SMS, payments, APIs).
  • Use @override_settings and Django's locmem email backend for testing.
  • Aim for 80%+ coverage on business logic.

DRF

  • Always use explicit fields in serializers — never __all__.
  • Use separate read/write serializers for nested data.
  • Set IsAuthenticated as the global default permission.
  • Always paginate list endpoints.
  • Use django-filter for declarative filtering.
  • Optimize get_queryset() with select_related/prefetch_related.

Signals

  • Import signals in AppConfig.ready(), never at module level.
  • Use dispatch_uid to prevent duplicate connections.
  • Prefer explicit method calls over signals for tightly coupled logic.
  • Use signals only for decoupled cross-app communication.

Caching

  • Use DummyCache in development, Redis in production.
  • Use namespaced cache keys with timeouts.
  • Invalidate targeted keys, never cache.clear().
  • Cache at the most granular level that makes sense.

Deployment

  • Never use runserver in production — use Gunicorn or Uvicorn.
  • Use multi-stage Docker builds.
  • Store secrets in environment variables, never in code.
  • Use zero-downtime deployment with Gunicorn HUP signal.
  • Always have a health check endpoint.

Background Tasks

  • Pass IDs to tasks, never model instances.
  • Always implement retry logic with exponential backoff.
  • Make tasks idempotent — safe to run more than once.
  • Use @shared_task instead of importing the Celery app directly.

Reference Files

Read the relevant reference file before writing code for that topic.

TopicFileWhen to read
Project structure & settingsreferences/core.mdSetting up a Django project, configuring settings, WSGI/ASGI, management commands
Model designreferences/models.mdCreating or modifying models, fields, relations, Meta options, managers, abstract/proxy models
ORM queriesreferences/queries.mdWriting queries, fixing N+1, using Q/F objects, aggregation, subqueries, transactions
Migrationsreferences/migrations.mdCreating migrations, data migrations, squashing, zero-downtime schema changes
Django Adminreferences/admin.mdConfiguring admin, inline models, custom actions, fieldsets, admin security/performance
Viewsreferences/views.mdWriting FBVs or CBVs, generic views, mixins, choosing between FBV and CBV
URL routingreferences/urls.mdConfiguring URLs, namespaces, path converters, reverse/reverse_lazy
Templatesreferences/templates.mdTemplate inheritance, tags, filters, custom template tags, context processors, security
Formsreferences/forms.mdDjango forms, ModelForms, validation, custom validators, formsets, file upload security
Authentication & sessionsreferences/auth.mdUser models, auth backends, login/logout, password reset, permissions, groups, sessions, cookies
Middlewarereferences/middleware.mdMiddleware order, custom middleware, exception handling, async middleware
Static & media filesreferences/static-media.mdStatic/media configuration, collectstatic, WhiteNoise, S3/CDN, file uploads, storage backends
Securityreferences/security.mdCSRF, XSS, SQL injection, clickjacking, password hashing, HTTPS, SECRET_KEY, security checks
Signalsreferences/signals.mdpre/post_save, pre/post_delete, m2m_changed, custom signals, when to avoid signals
Cachingreferences/caching.mdCache backends, Redis, per-view/fragment/low-level caching, invalidation strategies
Internationalizationreferences/i18n.mdi18n settings, gettext/gettext_lazy, translation tags, timezone support, locale structure
Testingreferences/testing.mdTestCase types, Client/RequestFactory, fixtures, pytest-django, factory_boy, mocking, coverage
Django REST Frameworkreferences/drf.mdSerializers, viewsets, routers, authentication, permissions, throttling, pagination, filtering
Background tasksreferences/celery.mdCelery setup, task definition, retries, queues, periodic tasks, Django-Q, Huey, idempotency
Deployment & performancereferences/deployment.mdGunicorn, Nginx, Docker, CI/CD, zero-downtime deploys, query optimization, indexing, async views
Django Channelsreferences/channels.mdASGI setup, WebSocket consumers, channel layers, group messaging, WS authentication, SSE
Django ecosystemreferences/ecosystem.mdDRF, django-filter, allauth, debug toolbar, storages, guardian, import-export, unfold, django-redis
Architecture patternsreferences/architecture.mdCustom fields, multi-DB, database routers, Jinja2, ORM internals, MTV, service layer, DDD, SOLID

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

39.91%
按下载量换算44

Claude

28.83%
按下载量换算31

Cursor

18.11%
按下载量换算20

Gemini CLI

9.06%
按下载量换算10

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills