Skip to content
Back to skills

Django Knowledge Patch

ASecurity

Django

  • 25 stars
  • 0 votes
  • 0 copies
  • 4 views
  • Added September 5, 2026
developmentjavascriptpythonrustgojavashellsqlexpressdjangotesting

Works with

  • cursor
  • api

Security analysis

A100/100

Pro scans all 10 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add Nevaberry/nevaberry-plugins --skill django-knowledge-patch --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Django Knowledge Patch?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Django Knowledge Patch
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/nevaberry-django-knowledge-patch-nevaberry-plugins/badge)](https://www.skillsdirectory.com/skills/nevaberry-django-knowledge-patch-nevaberry-plugins)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: django-knowledge-patch
description: Django
version: "6.1.3"
license: MIT
metadata:
  author: Nevaberry
---


# Django Knowledge Patch

Load this skill when upgrading Django or working on the APIs and behaviors below.
It covers compatibility changes, deprecations, and implementation guidance for
ORM queries, tasks, security, email, GIS, templates, forms, admin, and tooling.
Use the topic references for complete guidance, examples, and version attribution.

## Reference index

| Reference | Topics |
| --- | --- |
| [Upgrading and compatibility](references/upgrading.md) | Runtime and database requirements, dependencies, REST framework, release catalog |
| [ORM and databases](references/orm-and-databases.md) | Fetch modes, saves, expressions, JSON, aggregates, composite keys, migrations, backend hooks |
| [HTTP, security, and authentication](references/http-security-auth.md) | Login, redirects, async authentication, CSP, passwords, sessions, cookies, language selection |
| [Email and feeds](references/email-and-feeds.md) | Named mailers, message serialization, attachments, call signatures, addresses, feed stylesheets |
| [Tasks](references/tasks.md) | Backends, enqueueing, transactions, scheduling, execution context, results, tests |
| [Templates, forms, and admin](references/templates-forms-admin.md) | Admin overrides, logging, admindocs, bound fields, media, template tags, pagination |
| [GIS and spatial features](references/gis.md) | Input validation, geometry limits, dimensions, spatial functions, GeoIP2, map widgets |
| [Tooling, testing, and serialization](references/tooling-testing-serialization.md) | Storage, static files, shell imports, commands, test fixtures, serializers, translation tooling |

## Breaking changes and deprecations

### Authentication and admin overrides

Django 6.1 removes the fallback to `request.user` in `login()` and to
`request.auser()` in `alogin()` when `user` is `None`. Pass the authenticated user
explicitly with `login(request, user)` or `await alogin(request, user)`.
A `RemoteUserMiddleware` subclass with a custom `process_request()` should also
override `aprocess_request()`; a synchronous-only override is deprecated.

Django 6.0 requires `request` in `ModelAdmin.lookup_allowed()` overrides:
use `lookup_allowed(self, lookup, value, request)`.
For custom deletion logging, migrate deprecated `ModelAdmin.log_deletion()` and
`LogEntryManager.log_action()` overrides to `log_deletions()` and `log_actions()`.
When `delete_selected` removes multiple objects, it bulk-creates `LogEntry` rows
and skips their `pre_save` and `post_save` signals.

### Mail configuration and message APIs

Configure backend aliases and options in `MAILERS`; select an alias with `using=`
when sending. `EMAIL_BACKEND` and related settings still work and are deprecated
ahead of Django 7.0. Set `ADMINS` and `MANAGERS` to lists of email address strings;
use strings such as `'"Ops" <ops@example.com>'` for display names.

Pass optional mail-helper parameters such as `fail_silently` and `connection` by
keyword. For `EmailMessage` and `EmailMultiAlternatives`, only `subject`, `body`,
`from_email`, and `to` can remain positional without a deprecation warning.

`EmailMessage.message(policy=...)` returns Python's `email.message.EmailMessage`
and defaults to `email.policy.default`. Use Python's `MIMEPart` for custom
attachments and catch `ValueError` for prohibited header characters:
`MIMEBase` and `BadHeaderError` are deprecated.
Review subclasses relying on private methods or withdrawn support for
`mixed_subtype`, `alternative_subtype`, and legacy `email.charset.Charset` values
for `encoding`. Django 7.0 removes `SafeMIMEText`, `SafeMIMEMultipart`, and
`forbid_multi_line_headers()` from `django.core.mail`, along with
`django.core.mail.message.sanitize_address()`.

### Query syntax and JSON semantics

Use `order_by=` in `ArrayAgg`, `JSONBAgg`, and PostgreSQL's `StringAgg`;
their `ordering=` keyword is deprecated. For cross-backend string aggregation,
import `StringAgg` from `django.db.models` and pass a literal delimiter as
`Value(", ")`. The PostgreSQL-specific class and plain-string delimiter syntax
are deprecated. Custom PostgreSQL aggregates can migrate from the deprecated
`OrderableAggMixin` to `allow_order_by = True` on an `Aggregate` subclass whose
SQL function accepts ordering.

Pass Python values such as `{"enabled": True}` to `JSONField`, its lookups, and
expressions; support for already encoded JSON literals has been removed.
In Django 7.0, an exact lookup with `None` on a `JSONField` matches SQL `NULL`;
pass `JSONNull()` to match a top-level JSON `null`.

In Django 7.0, `values_list(flat=True)` raises `TypeError` without an explicit
field; use `queryset.values_list("pk", flat=True)` for primary keys.
A percent sign in a column or annotation alias raises `ValueError` in Django 7.0;
use a name such as `completion_pct`.

### Custom hooks, schema changes, and storage

Return a tuple of parameters from custom `as_sql()`, `process_lhs()`, and
`process_rhs()` methods. Use `(*lhs_params, *rhs_params)` to combine inputs that
may be lists on older Django versions. A single model save can call
`Field.pre_save()` more than once; keep custom implementations idempotent and
free of side effects.

Custom backends should rename `return_insert_columns()` to `returning_columns()`
and consolidate old fetch hooks into `fetch_returned_rows(cursor, returning_params)`.
The base and PostgreSQL schema editors drop columns without `CASCADE`;
drop dependent objects such as unmanaged views before removing the column.
Django 7.0 removes the `serialize` keyword from `BaseDatabaseCreation.create_test_db()`;
drop it from calls and update custom backend overrides.

Saving a nameless file through `FileField` raises `FieldError`;
supply a name, for example `ContentFile(b"report", name="report.txt")`.
Replace overwrite-related overrides of deprecated `FileSystemStorage.OS_OPEN_FLAGS`
with `FileSystemStorage(allow_overwrite=True)`.
Use `find(path, find_all=True)` in `django.contrib.staticfiles.finders`;
the `all` keyword is deprecated.

## ORM queries and persistence

### Deferred fields and saved values

Use `QuerySet.fetch_mode()` to control missing-field access. `FETCH_ONE` keeps
per-instance behavior, `FETCH_PEERS` fetches the missing field for peer instances
from the same queryset, and `FETCH_RAISE` raises `FieldFetchBlocked` on access.
In Django 6.1.3, peer loading preserves values changed in memory or explicitly
loaded with `refresh_from_db(fields=...)` and handles peers whose rows were deleted.

After `save()`, Django refreshes generated fields and fields assigned expressions
on SQLite, PostgreSQL, and Oracle. On MySQL and MariaDB, it defers those fields
and fetches their values when accessed. Catch `Model.NotUpdated` when a forced
update such as `instance.save(force_update=True)` affects zero rows.
Set `ForeignKey.on_delete` to `DB_CASCADE`, `DB_SET_NULL`, or `DB_SET_DEFAULT`
to have the database apply the deletion action.

### Composite keys and custom expressions

`makemigrations` can detect changes to an existing table's composite key even
when Django cannot apply the generated operations. Apply backend-specific SQL
first and record the migration with `migrate --fake`, or pair SQL and state
operations in `SeparateDatabaseAndState`.

`ForeignObject` with explicit local columns supplies an ORM join to a composite
key. This is an internal API; manage columns, constraints, indexes, and deletion
behavior separately. An index, constraint, or `unique_together` entry naming a
`ForeignObject` with multiple `from_fields` fails system checks; specify the
component fields directly. Use `Model._meta.pk_fields` to discover key fields.

`Count("pk")` accepts a composite key. Single-column functions such as `Max`
raise `ValueError` for `"pk"`; use a component such as `Max("order_id")`.
Set `allows_composite_expressions = True` on expressions that can consume
multi-column values. Set `set_returning = True` on an expression wrapping a
set-returning function to force subquery evaluation and preserve produced rows.

## Content Security Policy and login middleware

Add `django.middleware.csp.ContentSecurityPolicyMiddleware`; configure directives
in `SECURE_CSP` for enforcement or `SECURE_CSP_REPORT_ONLY` for monitoring.
For template nonces, enable `django.template.context_processors.csp` and include
`CSP.NONCE` in the directive. Use `nonce="{{ csp_nonce }}"` on the intended script
or style element to trigger lazy nonce generation. Generate the HTML and CSP
header together for each request and keep nonce-bearing responses out of
full-page caches.

Import `csp_override` and `csp_report_only_override` from
`django.views.decorators.csp` for per-view enforced and report-only policies.
A complete directive mapping replaces the corresponding global policy;
an empty mapping suppresses that header. For violation reports, add a reporting
directive such as `"report-uri": "/csp-reports/"` to the report-only policy and
supply an application report receiver or use a monitoring service.

With `django.contrib.auth.middleware.LoginRequiredMiddleware` in `MIDDLEWARE`,
set a view's `login_url` and `redirect_field_name` through `login_required()`.
The middleware runs before `LoginRequiredMixin` can apply its redirect settings.

## Background tasks

The default `django.tasks.backends.immediate.ImmediateBackend` executes during
enqueue. For durable background execution, one option is to install `django-tasks`,
add `django_tasks` and `django_tasks.backends.database` to `INSTALLED_APPS`, use
`django_tasks.backends.database.DatabaseBackend` in `TASKS`, run
`python manage.py migrate`, and start `python manage.py db_worker` separately.

Use `@task` on a module-level function and call `enqueue()` or await `aenqueue()`
with arguments that preserve their types through a JSON round trip, even with
the immediate backend. Return JSON-serializable values. Register enqueueing with
`transaction.on_commit()` when a worker on another connection needs rows written
by the transaction.

Set `run_after` with `Task.using()`, which returns a new task. Pass an aware
datetime or relative `timedelta` to a backend with `supports_defer`.
Priorities range from -100 to 100, with higher values first on backends that order
by priority. `queue_name` must be listed in the backend's `QUEUES` unless that list is empty.

On a backend with `supports_get_result`, use `result.refresh()` or
`await result.arefresh()` to update the snapshot. Both built-in backends raise
`NotImplementedError` on lookup. Task-level lookup raises `TaskResultMismatch`
for another task's ID; use `task_backends[alias].get_result(result_id)` from
`django.tasks` when the task function is unknown.
Check for `TaskResultStatus.SUCCESSFUL` before reading `result.return_value`,
which raises `ValueError` for unfinished or failed tasks. Inspect `result.errors`
for `TaskError` entries containing `exception_class` and formatted `traceback`.

## Forms, templates, and admin

Customize field binding with `BaseRenderer.bound_field_class`,
`Form.bound_field_class`, or `bound_field_class` on an individual field.
`BoundField.aria_describedby` exposes description IDs; `ErrorList(field_id=...)`
lets error templates emit an ID that the field's `aria-describedby` can reference.
Use `Script` in a `Media` JavaScript list to add script-tag attributes.

`ModelAdmin.list_display` accepts related-field paths such as `"author__name"`.
Named fieldsets with the `collapse` class render using `<details>` and `<summary>`,
including on inlines; update custom templates that load removed `collapse.js`.
Use `{% block extrabody %}` in templates extending `admin/base.html` to insert
markup immediately before `</body>`.

`simple_block_tag()` functions take the rendered block as their first argument;
close the block with `end` followed by the tag name. Pass multiple mappings to
`{% querystring %}`; the tag supplies the leading `?`.

## GIS input handling

Spatial lookups reject dictionaries and strings that cannot be parsed as a
`GEOSGeometry`. Model field assignments accept both input types, so validate
untrusted raster inputs before assigning them.
WKT allows a maximum `GEOMETRYCOLLECTION` nesting depth of 198; WKB allows at most
198 `GEOMETRYCOLLECTION` objects in total. Customize `max_geom_collections` on
`GEOSGeometry` or a form or model `GeometryField`. GeoJSON inputs are exempt.

## Testing and tooling

`SimpleTestCase` enforces its database-access restriction in threads; threaded
tests needing a database require a database-enabled test case.
`TransactionTestCase.setUpClass()` can access fixture data and data restored
from migrations with `serialized_rollback=True`.
Use `django.tasks.backends.dummy.DummyBackend` to record enqueued tasks without
executing them. Import `default_task_backend` from `django.tasks`, inspect its
`results` list in enqueue order, and call `clear()` between tests.
Use `collectstatic --verbosity 2` to see skipped files and files deleted by
`--clear`; verbosity 1 reports summaries for those files.

Files in this skill

  • SKILL.md9.2 KB
  • coverage.json1.2 KB
  • references/email-and-feeds.md3.9 KB
  • references/gis.md3.5 KB
  • references/http-security-auth.md6 KB
  • references/orm-and-databases.md10 KB
  • references/tasks.md3.2 KB
  • references/templates-forms-admin.md5 KB
  • references/tooling-testing-serialization.md4.5 KB
  • references/upgrading.md5.8 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.