Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Django Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-django-knowledge-patch)
---
name: django-knowledge-patch
description: Django
version: "6.1.3"
license: MIT
metadata:
author: Nevaberry
---
# Django Knowledge Patch
Load this skill when upgrading Django applications or working with the ORM,
authentication, CSP, tasks, email, GIS, templates, admin, or test tooling.
Use the quick reference for compatibility changes and common APIs, then open
the relevant topic file for complete guidance, examples, and version attribution.
## Reference index
| Reference | Topics |
| --- | --- |
| [Email and feeds](references/email-and-feeds.md) | Mailer aliases, message serialization, attachments, alternatives, feed stylesheets |
| [GIS](references/gis.md) | Spatial input limits, OGR, SRIDs, backend functions, GeoIP2, map widgets |
| [HTTP, security, and authentication](references/http-security-auth.md) | Login, async authentication, CSP, sessions, cookies, redirects, language codes |
| [ORM and databases](references/orm-and-databases.md) | Deferred fields, saves, composite keys, expressions, aggregates, JSON, migrations, backend hooks |
| [Tasks](references/tasks.md) | Backends, enqueueing, transactions, scheduling, context, results, failures |
| [Templates, forms, and admin](references/templates-forms-admin.md) | Admin overrides, logging, form rendering, template tags, pagination |
| [Tooling, testing, and serialization](references/tooling-testing-serialization.md) | Shell imports, command hooks, tests, serializers, static files, storage |
| [Upgrading](references/upgrading.md) | Runtime and database requirements, driver compatibility, REST framework, release catalog |
## Breaking changes and deprecations
### Login 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)`.
Django 6.0 requires `request` in `ModelAdmin.lookup_allowed()` overrides:
use `lookup_allowed(self, lookup, value, request)`.
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.
A `RemoteUserMiddleware` subclass with a custom `process_request()` should also
override `aprocess_request()`; a synchronous-only override is deprecated.
### JSON values and query results
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`.
```python
from django.db.models import JSONNull
sql_nulls = Event.objects.filter(data=None)
json_nulls = Event.objects.filter(data=JSONNull())
```
In Django 7.0, `values_list(flat=True)` raises `TypeError` without an explicit
field; use `queryset.values_list("pk", flat=True)` to retrieve primary keys.
A percent sign in a column or annotation alias raises `ValueError` in
Django 7.0; use a name such as `completion_pct`.
`BinaryField` now validates Base64 input strictly, so malformed strings can fail
where they previously decoded.
### Custom SQL, fields, and backend hooks
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.
Implement the `cache_name` cached property in custom `FieldCacheMixin`
subclasses that override the deprecated `get_cache_name()` method.
Django 7.0 removes the shim that let `Field.get_placeholder_sql()` call a
custom field's legacy `get_placeholder()`; implement `get_placeholder_sql()`.
Custom backends should rename `return_insert_columns()` to `returning_columns()`
and consolidate the old fetch hooks into `fetch_returned_rows(cursor, returning_params)`.
Set `DatabaseFeatures.can_return_rows_from_update = True` if the backend supports
`UPDATE … RETURNING`. Custom backends that need decimal adaptation must implement
it in their backend hook: `BaseDatabaseOperations.adapt_decimalfield_value()`
returns the supplied value unchanged.
### Schema changes and composite keys
The base and PostgreSQL schema editors now drop columns without `CASCADE`.
Drop dependent objects such as unmanaged views before removing the column.
`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 generated migration with `migrate --fake`, or pair SQL and
state operations in `SeparateDatabaseAndState`.
Use `ForeignObject` with explicit local columns to join to a composite key.
This internal API supplies the ORM join; manage columns, constraints, indexes,
and deletion behavior separately. An index, constraint, or `unique_together`
entry naming a `ForeignObject` with multiple `from_fields` now fails system
checks; specify the component fields directly.
### Email configuration and extension points
Configure backend aliases and options in `MAILERS`; select an alias with `using=`
when sending email. `EMAIL_BACKEND` and its related settings still work and are
deprecated ahead of Django 7.0.
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`.
Set `ADMINS` and `MANAGERS` to lists of email address strings; replace
`("Ops", "ops@example.com")` entries with `'"Ops" <ops@example.com>'` for display names.
### Aggregates, admin logging, and file storage
Use `order_by=` in `ArrayAgg`, `JSONBAgg`, and PostgreSQL's `StringAgg`;
their `ordering=` keyword is deprecated. Import cross-backend `StringAgg`
from `django.db.models` and pass a literal delimiter as `Value(", ")`.
The PostgreSQL-specific class and its plain-string delimiter syntax are deprecated.
Set `allow_order_by = True` on an `Aggregate` subclass whose SQL function accepts
ordering; custom PostgreSQL aggregates can migrate from `OrderableAggMixin`.
When `delete_selected` removes multiple objects, it bulk-creates `LogEntry`
rows and skips their `pre_save` and `post_save` signals. Migrate deprecated
`ModelAdmin.log_deletion()` and `LogEntryManager.log_action()` overrides to
`log_deletions()` and `log_actions()` for custom logging.
Named fieldsets with `collapse` now use `<details>` and `<summary>`, including
on inlines; update custom admin templates that load the removed `collapse.js`.
Saving a nameless file through `FileField` raises `FieldError`; supply a name,
for example `ContentFile(b"report", name="report.txt")`.
Replace overwrite-related `FileSystemStorage.OS_OPEN_FLAGS` overrides with
`FileSystemStorage(allow_overwrite=True)`.
Use `find(path, find_all=True)` in `django.contrib.staticfiles.finders`;
the `all` keyword is deprecated.
### Tests, pagination, and removed email helpers
`SimpleTestCase` enforces its database-access restriction in threads, so threaded
tests needing a database require a database-enabled test case.
Django 7.0 removes `serialize` from `BaseDatabaseCreation.create_test_db()`;
drop it from calls and update custom backend overrides.
In Django 7.0, `orphans` must be strictly less than `per_page` for both
`Paginator` and `AsyncPaginator`.
Django 7.0 removes `SafeMIMEText`, `SafeMIMEMultipart`, and
`forbid_multi_line_headers()` from `django.core.mail`, along with
`django.core.mail.message.sanitize_address()`.
## Frequently used features
### Deferred fields and model saves
Use `QuerySet.fetch_mode()` to select missing-field behavior: `FETCH_ONE` keeps
per-instance fetching, `FETCH_PEERS` fetches the missing field for peer instances
from the same queryset, and `FETCH_RAISE` raises `FieldFetchBlocked` on access.
With `FETCH_PEERS`, the deferred-field fetch preserves peer values changed in
memory or loaded explicitly with `refresh_from_db(fields=...)` and handles peers
whose database rows have been 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.
### Content Security Policy
Add `django.middleware.csp.ContentSecurityPolicyMiddleware` and 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`
to control a view's enforced and report-only policies, respectively. A complete
directive mapping replaces the corresponding global policy; an empty mapping
suppresses that header.
### Tasks and transaction timing
The default `django.tasks.backends.immediate.ImmediateBackend` runs each task
during enqueue. For durable background execution, one option is `django-tasks`;
see the task reference for database-backend setup and worker commands.
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 the enqueue
call with `transaction.on_commit()` when a worker on another connection needs
rows written by the transaction.
`Task.using()` returns a new task. For a backend with `supports_defer`, set
`run_after` to an aware datetime or relative `timedelta`. 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.
Check for `TaskResultStatus.SUCCESSFUL` before reading `result.return_value`,
which raises `ValueError` for unfinished or failed tasks.
### Forms, templates, and redirects
Customize bound fields 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 an error template emit an ID that
the field's `aria-describedby` can reference.
Use `Script` in a `Media` JavaScript list to add HTML attributes to the script tag.
A function registered with `simple_block_tag()` takes the rendered block as its
first argument; close the block with `end` followed by the tag name.
Pass multiple mappings to `{% querystring %}`; the tag supplies the leading `?`.
Set `RedirectView.preserve_request` to keep the request method and body when
the client follows the redirect.