Blog

Claude Code for Django: Configuration, guardrails and workflow

Goon Nguyen•Claude Code Guides••31 min read

Claude Code for Django: Configuration, guardrails and a reviewable development workflow

A useful Claude Code Django setup starts with accurate repository instructions, selective task guidance, and controls over what the agent can execute. It does not require a large configuration library. The goal is to produce changes that developers can inspect, validate, and reverse-with database and external effects considered separately. This guide assumes Claude Code is installed and authenticated. For installation and current feature behavior, consult Anthropic’s official Claude Code documentation.

Claude Code for Django: Configuration, guardrails and workflow

Audit the Django repository before configuring Claude Code

Configuration should describe the repository you have, not an idealized Django stack copied from a template. Begin by establishing both the code’s conventions and the systems that command execution could affect.

Record the stack, structure, and local conventions

Inspect dependency files, runtime configuration, maintained documentation, and representative code. Record:

  • Python and Django versions.
  • Project layout, installed apps, and app responsibilities.
  • Settings modules and how environments are selected.
  • Database engine and connection configuration, without copying credentials.
  • URL namespacing.
  • View patterns: function-based, class-based, DRF, or a mixture.
  • Templates and frontend tooling.
  • Where business rules live: forms, models, services, managers or QuerySets, serializers, or views.
  • Architecture and contribution documentation.
  • Optional components actually present, such as HTMX, DRF, Celery, or Channels.

Mixed conventions are not necessarily a problem. A repository may use class-based views for customer forms and function-based views elsewhere. Identify the pattern in the affected flow rather than asking Claude Code to standardize the entire project.

In the appointment example, preserve the existing class-based view pattern unless there is a reviewed reason to change it. Do not introduce HTMX because a reusable configuration mentions it. In another repository, do not generate pytest tests when the established runner and fixtures use Django TestCase.

Identify exact commands and their environment

A command is useful guidance only when its working directory, settings, dependencies, and effects are understood. Find the repository’s actual commands for:

  • Targeted tests and the full test suite.
  • Formatting checks and formatting that writes files.
  • Linting and type checking, when configured.
  • Django system checks.
  • Missing-migration checks.
  • Browser or integration verification.
  • The sequence used in CI.

Also record required environment-variable names, test database requirements, and fixture or factory conventions. Do not record secret values. Do not assume the repository uses uv, Ruff, Pyright, or Factory Boy. If it does, describe their roles correctly: Ruff provides linting and formatting; Pyright provides static type checking. They are not interchangeable checks.

For a conventional layout, these are recognizable Django commands:

python manage.py check
python manage.py makemigrations --check --dry-run

They are examples, not commands to run blindly. The repository may use a wrapper, a different manage.py location, containers, or explicit settings selection. Verify the installed Django version and its migration-command behavior; --dry-run makes the non-writing intent explicit, while historical handling of --check can differ.

For the running example, pytest-django is established, but the exact test path is not. Locate the affected app and inspect the configured runner before writing a targeted command into CLAUDE.md.

Classify effects before running commands

“Run checks” sounds harmless, but tests and management commands execute application code. That code may initialize services, write files, or contact external systems.

Action

Potential effect

Control to establish

Inspect tracked source files

May expose sensitive content in files

Exclude credentials and secret-bearing files; inspect only relevant material

Format or generate files

Changes the working tree

Separate check mode from write mode; inspect the diff

Run tests

Writes test databases, caches, files, or unintended services

Confirm isolated settings and mocked or disabled external calls

Run Django management commands

Imports settings and application code; may access systems

Review the command and startup behavior before execution

Apply migrations or import data

Changes database schema or records

Confirm the database target and obtain explicit approval

Use integrations or deployment tools

Writes tickets, sends messages, triggers CI, or affects shared systems

Restrict permissions and require approval at consequential boundaries

These represent effect categories rather than mutually exclusive groups. A single test command can modify files, query a database, and send a message if the environment is misconfigured.

Read-only planning should mean source inspection without executing application code or management commands unless separately approved. Asking the agent not to edit files does not create an execution sandbox.

Produce a small audit artifact

For the appointment application, the initial audit can look like this:

Area

Established fact or open question

Configuration consequence

Tests

pytest-django; app-local tests/ packages

Preserve runner and layout; inspect existing fixtures before selecting helpers

Views

Appointment flows use class-based views

Preserve that pattern unless the reviewed plan justifies a change

Frontend

Django templates; HTMX unconfirmed

Do not introduce HTMX without evidence or approval

Validation

Existing appointment form-validation pattern

Locate and reuse the relevant rules rather than duplicating them

Notifications

Implementation not yet inspected

Identify current behavior before changing transaction or delivery boundaries

Database

PostgreSQL

Inspect concurrency protections and migrations; database choice alone proves neither safety nor correctness

Authorization

Existing ownership checks

Locate the enforcement point and test direct requests, not just UI visibility

This separates known facts from unresolved questions. Only stable, confirmed findings should become persistent repository instructions.

Build a CLAUDE.md that describes this repository

CLAUDE.md provides persistent project guidance for Claude Code. It is not an executable policy, a permission boundary, or the repository’s definitive source of truth. Its job is to make important conventions and workflow constraints easy to find, particularly those that are not obvious from a few source files.

Include durable architecture and workflow instructions

The following is a starter content structure. Replace its descriptions with verified project facts before relying on it:

# Project overview

## Runtime and framework
Record verified versions and important installed components.

## Repository structure
Describe app responsibilities and architectural boundaries.

## Development commands
Record exact approved commands, settings, and environment requirements.

## Established Django conventions
Describe view, validation, business-rule, URL, and template patterns.

## Testing expectations
Record the runner, layout, fixtures, and required behavior coverage.

## Restrictions and approval points
Identify model changes, migrations, security changes, dependencies,
external writes, and shared-environment operations requiring approval.

## Definition of done
Specify checks, review expectations, and the completion-report format.

## References
Point to maintained repository documentation and relevant task guidance.

This is not a required universal format. Use headings that fit the repository, and avoid copying an entire Django manual into the file. References help navigation, but mentioning another file does not prove that Claude Code has read it. Likewise, referencing a skill does not establish that it was loaded or applied.

Replace vague ideals with observable instructions

Concrete instructions give reviewers something to evaluate.

Weak instruction

Stronger instruction for the example

“Use Django best practices.”

“Preserve the appointment app’s class-based view pattern; do not refactor adjacent views without approval.”

“Write good tests.”

“Use pytest-django in the app’s existing tests/ package and reuse established fixtures or factories where available.”

“Optimize queries.”

“Inspect actual related-object access and query behavior before changing loading strategies.”

“Keep it secure.”

“Preserve ownership enforcement and test a direct update request from another authenticated customer.”

“Run all checks.”

“Run the documented completion checks; report exact commands, results, and checks omitted.”

The query instruction matters because common ORM advice can become mechanical. select_related() typically joins single-valued relationships, such as foreign keys and one-to-one relationships. prefetch_related() uses separate queries and can serve multi-valued relationships. Neither is an unconditional optimization: the right choice depends on the data the flow actually accesses.

Add negative constraints and approval points

Document changes that require a deliberate decision:

  • No new dependency or architectural layer without a requirement and approval.
  • No HTMX, DRF, Celery, or Channels merely because a configuration template includes it.
  • No rewriting passing tests solely to accommodate new implementation behavior.
  • Review model changes before generating migrations, then review migration files before applying them.
  • Authentication does not establish object-level authorization.
  • No production or shared-service credentials in ordinary local workflows.
  • No completion claim without a validation report.

A task-relevant excerpt might be:

## Appointment changes

- Preserve existing ownership enforcement and form-validation conventions.
- Inspect current eligibility and availability rules before editing.
- Do not add a migration unless the reviewed plan requires a model change.
- Preserve notification behavior unless the feature brief changes it.
- Cover owner success, non-owner rejection, ineligible appointments,
invalid or unavailable times, and unchanged state after rejection.
- Report checks run, checks omitted, and browser verification status.

These instructions complement tool permissions and environment controls. They do not prevent an operation by themselves.

Separate product requirements from repository guidance

Different artifacts answer different questions:

Artifact

Question it answers

Appointment example

PRD: product requirements document

What larger product problem and behavior should be delivered?

A broader redesign of customer booking management

Feature brief

What should this bounded change do?

Customers may reschedule eligible appointments they own

CLAUDE.md

How should work proceed in this repository?

Preserve existing authorization and testing conventions

Architecture documentation and code

How does the current system work?

Where eligibility, availability, and notifications are implemented

A small fix does not require a full PRD. It does require enough behavioral clarity to distinguish a correct change from a plausible implementation.

For example, an unresolved rescheduling cutoff belongs in the feature discussion. It should not accidentally become a permanent “24 hours before the appointment” rule in CLAUDE.md.

Remove stale and conflicting context

Review persistent instructions when the repository changes. Remove obsolete commands, unused technologies, duplicated rules, and copied guidance that does not apply. There is no universal ideal line count. The useful test is whether each instruction helps the agent make a decision that matters in this repository.

When code and instructions disagree, investigate. The code may contain a bug, the instructions may be stale, or the current task may intentionally change an old convention. Automatically trusting either side can preserve the wrong behavior.

Create Django skills only when recurring tasks justify them

A skill supplies reusable guidance for a particular kind of work. It is not a mandatory child of CLAUDE.md, a security boundary, or protection against all incorrect output.

Decide whether guidance needs a skill

A skill is useful when the guidance:

  • Applies to a recurring subset of tasks.
  • Needs more detail than a short persistent instruction.
  • Has recognizable activation conditions.
  • Reflects the actual repository.
  • Includes patterns, anti-patterns, and validation steps.

Keep short, broadly applicable rules in CLAUDE.md. Reference maintained technical documentation rather than duplicating it in several skills. Potential subjects include forms, tests, models and QuerySets, migrations, templates, debugging, and-where actually used-DRF, HTMX, Celery, or Channels.

A Django Forum discussion describes a nine-skill community configuration, and the related waldencui/claude-code-django repository illustrates modular project guidance. These are examples of how developers organize configuration, not evidence that every Django project needs nine skills or that the setup guarantees better results.

Use a repository-specific SKILL.md

An illustrative repository-local location is:

.claude/skills/django-form-conventions/SKILL.md

Claude Code for Django: Configuration, guardrails and workflow

Its contents could be:

---
name: django-form-conventions
description: Use when changing Django forms, validation, or form submissions.
---

# Django Form Conventions

## When to use
- Add or change field or cross-field validation.
- Change an existing form submission flow.

## Core patterns
- Inspect representative forms and their callers first.
- Follow the repository's field and cross-field validation conventions.
- Preserve error rendering and existing ownership enforcement.
- Keep eligibility and availability rules in their established locations.

## Anti-patterns
- Treating hidden UI controls as authorization.
- Adding HTMX responses to a non-HTMX flow.
- Replacing existing forms with a new abstraction for one small feature.
- Assuming a pre-save availability check prevents concurrent bookings.

## Validation
- Targeted form and view tests.
- Rejection tests that assert unchanged stored state.
- Browser or integration verification for visible behavior.

This example illustrates content organization. Verify file discovery, supported frontmatter, and invocation behavior against the installed Claude Code version and its official documentation.

A skill’s description should help identify when it is relevant, but configuration text alone does not prove activation. Check the available diagnostics and observe whether the resulting plan follows the guidance.

Select only the guidance the appointment task needs

Start with form-validation or testing guidance if the audit reveals a recurring gap. Query guidance becomes relevant when the change affects related-object loading; it is not automatically necessary for every appointment change.

A migration skill is relevant only if an approved model change requires migration work. Celery guidance matters only if the project uses Celery and the task touches that behavior. The same condition applies to DRF and HTMX.

Do not build several skills simply to perform the example once. First establish which explanation you repeatedly need.

Match each Claude Code component to a clear responsibility

Configuration becomes easier to reason about when each mechanism has a distinct job.

Component

Responsibility

Django use

Boundary

CLAUDE.md

Persistent repository instructions

Conventions, commands, approval points

Does not enforce permissions

Skill

Reusable specialized guidance

Forms, testing, API permissions

Applicability and loading must be checked

Slash command or explicit skill invocation

User-started reusable action or workflow

Start a documented quality sequence

Invocation is not evidence of success

Agent or subagent

Delegated role or task context

Review a patch against conventions

Not an independent security audit

Hook

Event-triggered configured behavior

Run a narrow check or block a defined action

Blocking depends on the supported event and configuration

MCP integration

Model Context Protocol connection to tools or context

Read an approved issue tracker

External content is not trusted instruction; access needs scoping

LSP/code intelligence

Language-server navigation and diagnostics

Symbol lookup or static type diagnostics

Requires appropriate support; does not establish runtime behavior

Git worktree

Separate checked-out files and branch state

Work on a feature separately

Shares repository resources and does not isolate databases or services

Claude Code for Django: Configuration, guardrails and workflow
Skills and slash commands can overlap: A skill may support explicit invocation. Do not assume they are mutually exclusive or always require separate directories.

Hooks also need careful interpretation. An event trigger does not make the invoked program infallible; a hook can run a flaky test or a nondeterministic review. A local branch-checking hook is a safeguard, not a substitute for server-side branch protection.

For the appointment task, a reasonable arrangement might be persistent ownership expectations in CLAUDE.md, an optional form skill, an explicitly invoked quality workflow, and an optional delegated review. A worktree can separate the files from other work, but any databases, caches, queues, credentials, and APIs still need their own isolation decisions.

Start with a minimum viable configuration

An initial setup may require only a verified CLAUDE.md and appropriate existing execution controls.

project/
├── CLAUDE.md
└── .claude/ # Add only when needed
├── settings.json # Project-scoped settings, if appropriate
└── skills/
└── django-form-conventions/
└── SKILL.md

Do not create empty settings, skills, agent definitions, or hooks just to match a template. Shared project settings should not contain secrets or machine-specific credentials.

Validate understanding without edits or execution

Before allowing implementation, use a source-only task with these boundaries:

  1. Inspect relevant source and configuration files only.
  2. Do not edit files, execute project code, call external integrations, or read credential files.
  3. Summarize the apps, settings structure, and appointment flow.
  4. Identify documented checks from repository files without running them.
  5. Name representative files supporting the conclusions.
  6. Classify likely command effects and list uncertainties.
  7. Compare the result with the human-prepared audit.

Use available permission restrictions as well as natural-language instructions. If access cannot be adequately scoped, use an environment containing only the approved material.

The result should be specific enough to check. “The project uses Django forms” is weak evidence of understanding. A useful summary identifies the relevant form, its caller, and where the validation decisions occur.

Test a read-only feature plan

Next, ask for a rescheduling plan that locates:

  • Ownership enforcement.
  • Eligibility and availability rules.
  • Forms, views, URLs, templates, and tests.
  • Notification behavior.
  • Existing concurrency protection.
  • Whether HTMX or Celery is present.
  • Whether model changes appear necessary.

Accept the plan when it identifies plausible files and supporting evidence, preserves local patterns, and exposes unresolved decisions. If the agent invents an eligibility cutoff or proposes a queue before inspecting notification behavior, correct the context before permitting edits. A correct summary is an early configuration check-not proof that future implementation will be correct.

Worked Django workflow: Rescheduling an appointment

Once the configuration passes source-only validation, move to one bounded implementation. Keep requirements, decisions, execution, and verification visible throughout the change.

Resolve requirements and approve a file-level plan

Inspect existing behavior before selecting an implementation. Resolve these questions:

  • What makes an appointment eligible for rescheduling?
  • Which time zone and time boundaries apply?
  • What represents an available slot, resource, or capacity?
  • How does the application respond to unauthorized requests?
  • When should notifications occur?
  • What prevents simultaneous conflicting reservations?

A file-level plan should explain which files will change and why, which tests will be added, whether models must change, and whether any new dependency or abstraction is justified.

For example, the plan might propose changes to an existing form, its class-based view, a template, and the app’s tests-but it must first locate their real paths. If availability already belongs in a domain helper, duplicating that logic in the view is not a harmless shortcut.

Do not select an HTTP response status, notification channel, resource model, or cutoff merely because it is common elsewhere. Reuse the application’s established contract or obtain a product decision.

Define expected behavior before implementation

Use an acceptance table to connect each requirement to observable verification:

Scenario

Expected behavior

Required verification

Owner submits an eligible, available time

Time changes successfully

Authorized success test and persisted-state assertion

Non-owner submits a direct update request

Update is rejected under existing response conventions

Object-level authorization test; unchanged state

Appointment is ineligible

Update is rejected

Eligibility boundary tests

Time is invalid

Existing validation response is used

Form/view test, including relevant time-zone boundaries

Time is unavailable

Update is rejected

Availability test

Any request is rejected

Original appointment remains unchanged

Refresh from the database and compare relevant fields

User-visible response is returned

Correct existing template or partial behavior

Browser/integration check; HTMX only if present

Notification is required

Existing delivery semantics are preserved

No notification for rejection; verify successful-change behavior

Two requests compete for one exclusive slot

Both must not successfully claim it

Concurrency design review and an appropriate integration test

The last row applies when the scheduling model defines exclusive capacity. Some systems allow several appointments within the same time window; their invariant must reflect that capacity rather than impose a single-booking rule.

For rejected requests, asserting only the response is insufficient. Reload the appointment from the database and compare the fields that must remain unchanged. This catches implementations that save something before returning a validation error.

Resolve the availability race explicitly

Suppose two eligible customers try to move different appointments into the same exclusive slot. Both requests query availability before either saves. Each sees the slot as free.

The decision criterion is not “Does the availability check work?” It is:

Does the implementation preserve the scheduling invariant when competing requests overlap?

Inspect the existing design for:

  • A database constraint appropriate to the data model.
  • Transaction and locking behavior.
  • A shared resource or slot record that can be locked appropriately.
  • A need for schema or design changes if the current structures cannot protect the invariant.

transaction.atomic() alone does not serialize competing availability checks. Locking each customer’s separate appointment row may leave the shared slot unprotected. Locking the rows returned by an availability query does not automatically lock an absent row representing “nothing booked yet.”

Claude Code for Django: Configuration, guardrails and workflow

Reuse a suitable existing mechanism when one is present. If none exists, stop for developer design review rather than inserting a generic locking recipe. A required constraint or resource representation may introduce a migration and expand the task’s scope. Verification should observe:

  • The final committed database state.
  • How many updates succeeded.
  • The response received by the unsuccessful request.
  • Whether notifications match committed outcomes.

Sequential unit tests cannot establish race safety. A concurrency test needs realistic transaction boundaries and the relevant PostgreSQL behavior; a test setup that masks concurrency or substitutes a different database may not exercise the problem.

Implement and test in inspectable increments

If the repository practices test-driven development, write the tests first. Otherwise, approve the test plan and include tests in the same change. Preserve existing passing tests unless a requirement justifies changing their expectations. A failing test identifies a mismatch; it does not automatically establish whether the implementation or the expectation is wrong.

Keep implementation within existing patterns. Do not add a service layer, signal, task queue, frontend library, or broad refactor without a demonstrated need.

An inspectable increment has a clear purpose and understandable rollback boundary. It is not defined by an arbitrary line-count limit. A coherent change across a form, view, template, and tests may be easier to review than several incomplete fragments.

Run layered validation

After confirming the isolated environment, use the audited commands in a deliberate sequence:

  1. Targeted tests during implementation.
  2. Broader relevant regression tests for connected appointment behavior.
  3. Formatting checks, linting, and configured type checks.
  4. Django system checks.
  5. Missing-migration checks using verified command behavior.
  6. Migration-file review and disposable-environment testing when schema changes are intended.
  7. Browser verification of the visible rescheduling flow.
  8. Human review of authorization, transactions, concurrency, and notifications.

For a conventional layout and approved environment, the Django checks might include:

python manage.py check
python manage.py makemigrations --check --dry-run

Use the repository’s real environment wrapper and settings selection where required. Do not treat these commands as evidence of deployment readiness. python manage.py check --deploy belongs in an appropriate deployment-settings context. It is not a mandatory command after every form edit.

Each validation layer has a limit:

  • Passing tests cover encoded expectations, not every product rule.
  • Migration-drift checks do not assess lock duration or rollout safety.
  • Static analysis does not establish runtime behavior.
  • Browser checks do not replace direct unauthorized-request tests.
  • Deployment checks depend on settings and do not replace operational review.

A useful validation report states what each layer actually checked rather than compressing everything into “all checks passed.”

Require an auditable completion report

The completion report should include:

  • Files changed and requirements addressed.
  • Tests added or changed.
  • Exact commands run and observed results.
  • Checks not run and reasons.
  • Migration status.
  • Assumptions and unresolved decisions.
  • Authorization, concurrency, notification, and deployment risks.
  • Manual verification performed or still required.

A command that could not run because the test database was unavailable is an omitted check, not a pass. A browser flow that was described but not exercised remains unverified.

Cademuir’s practitioner account of developing a Django application with Claude supports the general value of planning, stack-specific instructions, testing, incremental work, using the application, and human intervention. The appointment workflow here is an instructional example, not a reported customer result or measured productivity outcome.

Keep human review mandatory for high-consequence changes

Review depth should follow the consequence of failure. A template wording change and a booking-availability constraint do not deserve identical treatment.

Protect test intent

Running tests, generating tests, interpreting failures, and deciding whether expectations should change are separate activities. An agent can produce implementation and tests that share the same incorrect assumption. Review the expectations against the feature requirements, not merely against the code being introduced.

Require explicit justification for weaker assertions, removed rejection cases, or fixtures changed to avoid difficult states. For the appointment feature, a non-owner rejection test should not disappear because the new implementation makes it fail.

Treat migrations as deployment changes

Review migration files for:

  • Renames versus destructive drop-and-recreate operations.
  • Data migrations and data preservation.
  • Constraints and incompatible existing data.
  • Nullability changes.
  • Index creation and possible locking.
  • Table size and operational duration.
  • Compatibility during rolling deployments.
  • Ordering across branches.
  • Reversibility and recovery planning.

A migration that works on an empty local database may fail or hold disruptive locks against production data. Reverting a Git patch does not reverse database or external effects. A worktree also does not provide a separate database. Use separately configured local or disposable environments when testing schema changes.

Review authorization and trust boundaries

For the affected flow, examine authentication, object permissions, sessions, CSRF protection, input validation, uploads, secrets, admin access, external callbacks, and cross-user data visibility. Include DRF permissions where DRF is actually present.

In the appointment example, ownership enforcement must happen server-side on direct requests. Hiding the reschedule button is a UI decision, not an authorization control. Successful authentication establishes who the user is, not which appointment they may modify.

An agent-generated review can surface questions and suspicious code. It is not a security audit or a substitute for accountable human review.

Restrict credentials and external actions

Start with narrowly scoped or read-only access where possible. Separate permission to:

  • Read an issue from permission to update it.
  • Edit code from permission to commit or open a pull request.
  • Run local checks from permission to deploy.
  • Send test messages from permission to notify real customers.

Keep secrets out of persistent instructions, generated reports, and logs. Issue text, repository content, and tool responses can contain untrusted instructions. They may supply task data, but they cannot authorize credential disclosure, broader permissions, or consequential actions.

Add hooks and commands according to their effects

Automate work after its manual behavior and boundaries are understood. A useful progression is:

  1. Source inspection.
  2. Isolated local validation.
  3. Reviewable file generation or formatting.
  4. Git history and repository workflow changes.
  5. External writes.
  6. Shared-environment and deployment operations.

This is an illustrative progression, not a universal risk ranking. Validation can be dangerous when it uses shared credentials, and file generation already changes repository files. Classify actual effects rather than trusting labels such as “check” or “quality.”

Start with visible local checks

Useful candidates include:

  • Showing the current branch and working-tree status.
  • Warning or blocking a supported edit path on main.
  • Running targeted tests with isolated settings.
  • Running existing lint and formatting checks.
  • Running Django checks and verified migration-drift checks.
  • Listing changed and untracked files.
  • Producing a review summary without silently committing.

Running the full suite after every edit is not universally useful. Choose frequency and scope based on execution cost, feedback value, and side effects.

Use a reusable quality workflow

A user-defined /quality or /code-quality invocation can organize the approved sequence. These names are illustrative, not built-in commands.

Its documentation should state:

  • The exact repository commands and their order.
  • Which commands are check-only and which modify files.
  • Whether a failure stops the sequence or allows later checks to continue.
  • How results and omitted checks are reported.
  • Which operations require approval.

For example, formatting in check mode should not silently become auto-formatting. If a modifying step is approved, the workflow should show the resulting diff. Invocation is only the start of the workflow. Success still requires observed results.

Make hook behavior inspectable

For every hook, record:

Hook property

What to document

Event

The supported trigger, such as PreToolUse or PostToolUse

Scope

Matcher and operations affected

Execution

Exact command and required environment

Writes

Whether files, databases, or external systems can change

Runtime behavior

Timeout and failure handling

Enforcement

Whether failure blocks an action or merely reports

Manual equivalent

How a developer reproduces the check

CI relationship

Which checks overlap and why

Local purpose

Why the hook is worth running at that point

Verify event-specific blocking behavior for the installed Claude Code version. A post-action hook cannot prevent an action that has already occurred, although it may report the result or affect subsequent behavior.

Delay automatic commits, pull requests, ticket transitions, dependency changes, and deployments until ownership and permissions are clear. Automation should make execution more predictable, not make side effects less visible.

Claude Code for Django: Configuration, guardrails and workflow

Troubleshoot Claude Code by symptom

When output disappoints, identify the missing context, requirement, or control before adding more configuration.

Output is generic or non-idiomatic

  • Possible cause: Claude Code has not seen representative files, the repository uses mixed patterns, or the task is too broad.
  • Corrective action: Identify the relevant local examples and add only the missing observable rule. Create a skill if the same gap recurs across tasks.
  • Check improvement: The revised plan should name and preserve the affected flow’s actual pattern—not merely promise to follow “Django best practices.”

The agent adds unnecessary abstractions

  • Possible cause: Copied template assumptions or no requirement to justify architecture changes.
  • Corrective action: Require a concrete need for services, base classes, signals, queues, packages, adapters, and broad refactors.
  • Check improvement: Each addition should map to an approved requirement that existing patterns cannot adequately satisfy. “This is cleaner” is not enough when it expands a bounded form change into an architectural rewrite.

Instructions appear to be ignored

  • Possible cause: Contradictions, stale guidance, vague wording, inactive guidance, or an oversized task.
  • Corrective action: Use version-supported diagnostics to confirm relevant guidance is loaded, remove conflicts, and request a summary of the applicable rules before editing.
  • Check improvement: Inspect the next bounded diff. Correctly restating an instruction is not proof that the implementation follows it.

Tests pass, but the feature is wrong

  • Possible cause: Missing authorization or concurrency cases, misleading fixtures, implementation-focused assertions, or shared assumptions between code and tests.
  • Corrective action: Return to the acceptance table and review expected behavior independently. Exercise rejected and adversarial paths as well as the happy path.
  • Check improvement: Confirm persisted state after rejection, direct non-owner requests, relevant time boundaries, and the actual user-visible flow.

Migration checks pass, but deployment is risky

  • Possible cause: A drift check is being treated as a deployment assessment.

Migration-drift checks do not evaluate existing data shape, lock duration, backward compatibility, branch ordering, reversibility, or rollout strategy.

  • Corrective action: Review the migration and deployment plan, then test against representative disposable data where appropriate.
  • Check improvement: The review should explain the operational effect and recovery approach—not merely show that no additional migration file is missing.

Hooks are slow or unpredictable

  • Possible cause: Overbroad triggers, repeated full-suite execution, hidden writes, unsuitable timeouts, or duplicated work.
  • Corrective action: Inspect trigger frequency, scope, blocking behavior, and execution cost. Run the manual equivalent to distinguish a hook configuration problem from an underlying tool failure.
  • Check improvement: Narrow or remove low-value hooks, then verify that the remaining ones run when intended and report failures clearly.

The agent loops or repeatedly fails

Stop rather than allowing an expanding sequence of speculative changes:

  1. Stop execution.
  2. Preserve and inspect the current diff.
  3. Identify verified and unverified changes.
  4. Revert only reviewed changes with developer approval; do not discard unrelated work.
  5. Reduce scope and restate the relevant constraints.
  6. Resolve architecture or security decisions manually.
  7. Resume with one bounded, testable step.

Repeated failure may indicate an unresolved requirement or design problem. More retries do not resolve that uncertainty by themselves.

"when to stop Claude Code and escalate in Django development"

Decide whether Claude Code fits the development task

Choose the working mode based on the access and coordination the task needs, not on a brand ranking.

Working mode

Useful for

Control consideration

Terminal-based repository agent

Multi-file inspection, coordinated edits, approved checks, repeatable repository workflows

Requires scoped permissions, environment controls, and review

Inline editor assistance

Small developer-directed edits and suggestions while typing

Local acceptance keeps changes explicit; this describes inline mode, not every capability of an editor product

Manually operated chat

Explanations, design discussion, isolated snippets, review of supplied code

No direct repository execution in this mode; context must be supplied and sensitive code handled carefully

The same product may offer several modes. Comparing Claude Code, Copilot, or Codex without current, comparable evidence would not establish which is best for your repository.

Claude Code is a plausible fit when a task benefits from repository inspection, coordinated changes, approved command execution, and inspectable reporting. Prefer a mode with less autonomy when:

  • The edit is tiny and developer-directed.
  • Repository access is inappropriate.
  • Verification is weak or unavailable.
  • Security, product, or architecture decisions remain unresolved.
  • Database or external side effects cannot be isolated.

Evaluate the quality of the resulting workflow rather than assuming more autonomy is always better.

Adopt Claude Code incrementally in Django projects

A bounded trial reveals which configuration is useful. Building an extensive configuration library first can encode assumptions you have not tested.

For an existing repository

Use this sequence:

  1. Audit the stack, conventions, commands, and effects.
  2. Add the smallest useful persistent instructions.
  3. Validate understanding through source-only analysis.
  4. Try a low-risk bug fix or bounded feature.
  5. Add one skill after observing a recurring guidance gap.
  6. Add a reusable local quality workflow.
  7. Introduce narrow hooks only after commands work manually.
  8. Add subagents, MCP, or CI integration for distinct needs.
  9. Remove obsolete configuration as the repository changes.

The appointment example includes meaningful authorization and concurrency concerns. It illustrates where review boundaries belong, but it is not necessarily the best first trial for an unverified setup.

For a new project

Record product and architecture decisions before generating substantial code. Establish settings separation, tests, Git practices, and the quality tools you actually intend to use.

Encode stable decisions rather than speculative architecture. A project without background jobs does not need a Celery skill, and an unresolved API strategy should not become a permanent DRF requirement.

Verify commands manually before automating them. Test deployment assumptions in a non-production environment, and keep unresolved security and architecture decisions under developer control.

Evaluate one bounded change

After the trial, ask:

  • Did the plan identify the correct files and unknowns?
  • Were existing conventions preserved?
  • Did tests cover required behavior and rejected requests?
  • Were execution and side effects visible?
  • Were unnecessary dependencies avoided?
  • Could reviewers understand and reverse the code change?
  • Were database and external effects considered separately?
  • Were omitted checks and unresolved risks disclosed?
  • Did reusable guidance reduce repeated explanation without hiding decisions?

These questions are more useful than counting skills, hooks, or configuration files. They assess whether the setup supports accountable development.

Frequently asked questions

Can Claude Code manage Django database migrations safely?

Claude Code can generate, inspect, and run migration commands, but it does not inherently guarantee safe deployment. To manage migrations safely, you should require the agent to generate migrations in a check-only mode and explicitly request human review of the generated migration files before applying them to any database.

Never assume that a migration that passes on an empty local environment will not cause locks or data loss in a production environment with existing records.

How do I prevent Claude Code from rewriting my established Django patterns?

You should document your project's specific conventions within a CLAUDE.md file located at the root of your repository. By explicitly stating these preferences as negative constraint, you provide the agent with the necessary context to adhere to your existing architectural choices rather than defaulting to generic stack templates.

Does using a skill guarantee that Claude Code will follow my specific rules?

No. While skills provide reusable guidance for recurring tasks, they are not a substitute for human supervision or a guarantee of perfect execution. A skill is a tool for context-loading; the agent must still decide when and how to apply those instructions. You should always treat the agent’s output as a proposal that requires verification, especially when the task involves complex authorization, concurrency, or sensitive data operations.

Should I create a separate skill for every Django component?

You should only create a skill if a specific guidance set is truly recurring and warrants more detail than a short entry in your CLAUDE.md. Creating a library of skills for every potential technology (like Celery, DRF, or Channels) before you actually need them often leads to context bloat and can degrade the agent's performance.

Start with a minimal configuration and add skills incrementally as you observe recurring gaps in the agent's ability to handle specific repository tasks.

What should I do if Claude Code enters a loop or fails to progress?

If the agent begins to repeat actions or fails to complete a task, stop the execution immediately. Review the diff to identify which changes are valid and which are not. Revert any unreviewed changes, reduce the scope of the task to a smaller, more bounded unit, and clarify the necessary constraints. Often, repeated failure indicates that the requirements, architectural expectations, or repository context are not sufficiently clear, and simply retrying the same task will not resolve the underlying uncertainty.

Read more:

Conclusion

A practical Claude Code workflow for Django depends on accurate context, selective guidance, visible actions, and testable changes. CLAUDE.md helps describe the repository; skills help with recurring tasks; permissions and environment controls limit execution; tests and human review evaluate the result.

Start with one repository audit and the smallest useful CLAUDE.md. Validate understanding without execution, then try a bounded, low-risk change. Add automation only when the underlying commands, side effects, and review responsibilities are already clear.

Share this article