Django 6.0 was released today, starting another release cycle for the loved and long-lived Python web framework (now 20 years old!). It comes with a mosaic of new features, contributed to by many.
Template Partials
The Django Template Language now supports template partials, making it easier to encapsulate and reuse small named fragments within a template file.
Partials are sections of a template marked by the new {% partialdef %} and {% endpartialdef %} tags. They can be reused within the same template or rendered in isolation.
Reuse partials within the same template
The below template reuses a partial called filter_controls within the same template:
<section id=videos>
{% partialdef filter_controls %}
<form>
{{ filter_form }}
</form>
{% endpartialdef %}
{% partial filter_controls %}
<ul>
{% for video in videos %}
<li>
<h2>{{ video.title }}</h2>
...
</li>
{% endfor %}
</ul>
{% partial filter_controls %}
</section>
Tasks Framework
Django now includes a built-in Tasks framework for running code outside the HTTP request–response cycle. This enables offloading work, such as sending emails or processing data, to background workers.
Define tasks with the new @task decorator:
from django.tasks import task
@task
def resize_video(video_id):
...
And enqueue them for background execution:
from example.tasks import resize_video
def upload_video(request):
...
resize_video.enqueue(video.id)
...
Content Security Policy Support
Built-in support for the Content Security Policy (CSP) standard is now available, making it easier to protect web applications against content injection attacks such as cross-site scripting (XSS).
To get started, add ContentSecurityPolicyMiddleware to your MIDDLEWARE setting:
MIDDLEWARE = [
# ...
"django.middleware.csp.ContentSecurityPolicyMiddleware",
# ...
]
Email API Updates
Email handling in Django now uses Python’s modern email API, introduced in Python 3.6. This API, centered around the email.message.EmailMessage class, offers a cleaner and Unicode-friendly interface for composing and sending emails.
Other Notable Changes
- Extended automatic shell imports: Common utilities, such as
django.conf.settings, are now automatically imported to the shell by default. - Dynamic field refresh on save():
GeneratedFields and fields assigned expressions are now refreshed from the database aftersave()on backends that support theRETURNINGclause. - Universal StringAgg aggregate: The new
StringAggaggregate returns the input values concatenated into a string, separated by the delimiter string. This aggregate was previously supported only for PostgreSQL. - BigAutoField as the default primary key type: The
DEFAULT_AUTO_FIELDsetting now defaults toBigAutoField.
For more details, check out the official release notes.