Enhancements Unveiled: Notable Features in Django 5

WebDev February 6, 2024
On this page
  1. Rendering form fields has been streamlined
  2. Model Fields for Computations and Generated Columns
  3. Field choices can be written with greater ease
  4. More Async View Decorators
  5. Exception Handling for Async Disconnects

Django, the comprehensive Python web framework, is approaching its fifth major release. Explore the following five significant features introduced in Django 5, ready to enhance your experience in both existing and upcoming Django projects.

Rendering form fields has been streamlined

In Django, form fields encompass various elements such as a descriptive label, help text, error label, and the field itself. Managing the layout of multiple fields manually in a form can become tedious.

To address this, Django 5 introduces a new method called .as_field_group for form fields. When utilized in a template, the .as_field_group method automatically renders all the elements within the field group, following a customizable template.

{{ form.client.label_tag }}
{% if form.client.help_text %}
<div class="client-helptext" id="{{ form.client.auto_id }}_client_helptext">
    {{ form.client.help_text|safe }}
</div>
{% endif %}
{{ form.client.errors }}
{{ form.client }}

... as just this:

{{ form.client.as_field_group }}

Once again, the presentation remains highly customizable. You can substitute the default template for field groups on an application-wide basis. Alternatively, you can tailor the template for each specific field or even customize it dynamically based on each request. This adaptability ensures that the presentation can be finely tuned to meet your specific requirements and preferences at various levels of granularity.

Model Fields for Computations and Generated Columns

In databases, computed columns empower you to specify a column's value as the outcome of a predefined formula, computed within the database before being transmitted to the client.

Django 5 introduces a novel capability by allowing the definition of fields in models with a database default parameter. This feature enables the provision of a database-computed default value. For instance, a DateTimeField could employ Now() as a default value.

It's important to highlight that the db_default parameter can exclusively be set to an output derived from a combination of literals and supported database functions.

Adding to the advancements in Django 5.0 is the introduction of GeneratedField—a fresh field type where the value is consistently generated from the values of other fields. The outcomes can be either stored in the database upon row creation or update (referred to as a "stored" field), or computed only when the row is retrieved (a "virtual" field).

Additionally, it's crucial to note that GeneratedFields are limited to using other fields within the same model as inputs. Furthermore, using other generated fields as a source is not supported; only actual fields can be utilized.

Field choices can be written with greater ease

In earlier iterations of Django, if you aimed to enumerate the choices accessible to Field.choices and ChoiceField.choices objects, you were required to build a cumbersome structure involving either 2-tuples or Enumeration subclasses:

FRUIT_DATA = [
("Fruits", [("apple", "Apple"), ("banana", "Banana")]),
("Citrus", [("orange", "Orange"), ("lemon", "Lemon")]),
("Exotic", "Tropical"),
]

With Django 5, you have the option to employ a more concise declaration utilizing dictionary mappings:

FRUIT_DATA = {
"Fruits": {"apple": "Apple", "banana": "Banana"},
"Citrus": {"orange": "Orange", "lemon": "Lemon"},
"Exotic": "Tropical",
}

This approach simplifies the encoding of choices as literals and also makes it a bit more straightforward to generate programmatically.

More Async View Decorators

Django introduced its initial support for Python's asynchronous mechanisms in version 3.0. However, not all aspects of Django immediately embraced async support; it has been incorporated progressively. Async views were introduced in version 4.0, and support for the ORM is expected in a forthcoming release.

Due to the incremental integration of async support in Django, several decorators were previously incompatible with wrapping async views. Version 5 marks a significant shift, as many more decorators are now capable of wrapping async views. Notably, this includes decorators that guarantee CSRF (cross-site request forgery) protection for views, enhancing their utility.

Exception Handling for Async Disconnects

When dealing with async connections, there is a constant concern that a lengthy connection might be terminated before Django provides a response. In earlier versions, there was no inherent mechanism to manage cleanup when an async connection was canceled. Django 5 addresses this by introducing an appropriate exception, asyncio.CancelledError, which can be caught and handled as necessary.