---
title: "Claude Code for Django: Configuration, guardrails and workflow"
description: "Learn how to configure Claude Code for Django projects. Set up repository instructions, guardrails, and reviewable workflows for secure, effective automation."
---

# Claude Code for Django: Configuration, guardrails and workflow

Published: 2026-09-21T04:59:15.941Z

Author: [Goon Nguyen](/author/goon)

Reading time: 31 minutes

Learn how to configure Claude Code for Django projects. Set up repository instructions, guardrails, and reviewable workflows for secure, effective automation.

# 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.

![Image](https://cdn.agentkit.best/blog/cfai-media/d3a31506ee42fba59a617c0fdbea4901de7373d347815792e8f62b9cb50a7e89-952fcfda83f12f120935bb64668ce8026d9715db8ab670e869966bf4d264bb36.jpg)

## 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:

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:

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](https://agentkit.best/blog/claude-code-guides/claude-code-claude-md-guide-best-practices-and-3-templates).

### 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.

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](https://agentkit.best/blog/claude-code-guides/claude-code-sandbox-a-guide-to-secure-ai-command-execution).

### Produce a small audit artifact

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

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.

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:

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:

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:

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
`

![Image](https://cdn.agentkit.best/blog/cfai-media/3d7f67ec993e1ddcdabdf0e8d706bd572a86348cfbd13f463b91aadd8b654048-39b7991f7ee6885f2f141189e337f57b19b57e4b8ae5b5dc14ce7517a10fab23.jpg)

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.

![Image](https://cdn.agentkit.best/blog/cfai-media/8141ad8af707cfdc1ab846227b87a97963cd06a87fe949d93f6eb30e9557d419-be79ddb9a8b2e95d11f415acd2912d4cddb9089d52e6f074f81ab605378bcda1.jpg)

> [*Skills*](https://agentkit.best/blog/claude-code-guides/claude-code-skills-best-practices-build-reusable-ai-workflows)* and *[*slash commands*](https://agentkit.best/blog/claude-code-guides/claude-code-slash-commands-essential-shortcuts-for-cli-flow)* can overlap: A skill may support explicit invocation. Do not assume they are mutually exclusive or always require separate directories.*

[Hooks](https://agentkit.best/blog/claude-code-guides/claude-code-hooks-guide-automate-and-control-ai-workflows) 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:

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:

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:

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:

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:

`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.”

![Image](https://cdn.agentkit.best/blog/cfai-media/2ae497d7a43f48b73f0a5bea0edd0c097157f3fa36d170e8dfa223d3ba50336d-ad5be476b9f9dacc98244280934232894074f0183f0d2a4a8bde213973fd6597.jpg)

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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.

![Image](https://cdn.agentkit.best/blog/cfai-media/92bf7044613544ed591e92a5efbd2b5680ed5cf5b11cb85e0525b000c75d1f12-ba4f117e9505f0c12907dc17aaec97c66e3a99fa0faee04fc13fb78b10783eac.jpg)

## 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

### The agent adds unnecessary abstractions

### Instructions appear to be ignored

### Tests pass, but the feature is wrong

### Migration checks pass, but deployment is risky

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

### Hooks are slow or unpredictable

### The agent loops or repeatedly fails

Stop rather than allowing an expanding sequence of speculative changes:

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

![Image](https://cdn.agentkit.best/blog/cfai-media/16a33051a9fbe8090e46979b98198dd4b21d774f52a0064d0e5a50eb1583d1c2-2bc5525341a6c1f7bf99e27bb8b96741783bab7bcc1776bb52847eff7406f971.png)

## 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.

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:

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:

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:

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.
