8 months ago | 25 min Read | 209
Hey Flox, last week Django released its 5.1 version. and it includes new features some are major changes and some are minor let’s discuss them one by one.
{% querystring %}
template tag:Django 5.1 include {% querystring %} template tag, simplifying how to change query parameters in URLs. This makes creating links that keep the existing query parameters easier while adding or modifying specific ones.
For example, working with pagination and query strings in templates can sometimes feel a bit tricky. Take a look at this template snippet that cheerfully creates a URL for moving to the next page in a paginated view:
{# Linebreaks added for readability, this should be one, long line. #}
<a href="?{% for key, values in request.GET.iterlists %}
{% if key != "page" %}
{% for value in values %}
{{ key }}={{ value }}&
{% endfor %}
{% endif %}
{% endfor %}page={{ page.next_page_number }}">Next page</a>
Switching to this new template tag is super easy! The above will magically transform into:
<a href="{% querystring page=page.next_page_number %}">Next page</a>
Django 5.1 is excited to introduce connection pool support for PostgreSQL! Since establishing a new connection can take some time, keeping connections open can help reduce latency and make everything run smoother.
To use a connection pool with psycopg, you can simply set the "pool"
option inside OPTIONS
to be a dictionary that gets passed to ConnectionPool
, or just set it to True
to use the default settings of ConnectionPool
. Easy and efficient!
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
# ...
"OPTIONS": {
"pool": {
"min_size": 2,
"max_size": 4,
"timeout": 10,
}
},
},
}
The new LoginRequiredMiddleware
kindly redirects all unauthenticated requests to a login page. If you want to allow unauthenticated requests, you can use the new login_not_required()
decorator.
The LoginRequiredMiddleware
respects the login_url
and redirect_field_name
values set via the login_required()
decorator. However, please note that it doesn't support setting login_url
or redirect_field_name
via the LoginRequiredMixin
.
To enable this feature, simply add "django.contrib.auth.middleware.LoginRequiredMiddleware"
to your MIDDLEWARE
setting.
django.contrib.admin
:Hey there! Great news! The ModelAdmin.list_display
now supports using __
lookups to list fields from related models. How cool is that?
django.contrib.auth
:The default iteration count for the PBKDF2 password hasher is bumped up from 720,000 to 870,000.
The default parallelism
of the ScryptPasswordHasher
is now increased from 1 to 5, following OWASP recommendations.
BaseUserCreationForm
and AdminPasswordChangeForm
now support turning off password-based authentication by setting an unusable password when saving the form. You can now find this feature in the admin when you visit the user creation and password change pages.
login_required()
, permission_required()
, and user_passes_test()
decorators now support wrapping asynchronous view functions.
ReadOnlyPasswordHashWidget
now includes a handy button to reset the user’s password, replacing the link that was previously in the ReadOnlyPasswordHashField
’s help text. This change makes the UserChangeForm
more accessible.
django.contrib.sessions
:**django.contrib.sessions.backends.cached_db.SessionStore
now gracefully handles exceptions when storing session information in the cache and logs helpful error messages with their traceback through the newly added sessions logger.
django.contrib.sessions.backends.base.SessionBase
and all built-in session engines now offer an async API. The new asynchronous methods come with an a
prefix, like aget()
, akeys()
, or acycle_key()
.
The allow_overwrite
parameter of FileSystemStorage
now lets you easily save new files over existing ones.
It's make things easier and help screen readers connect fieldsets with their help text, we've added the aria-describedby
HTML attribute to the form fieldset.
The makemigrations
command now shows some really helpful symbols for each operation to highlight operation categories
.
The new Operation.category
attribute lets you specify an operation category
. This is used by makemigrations
to show a meaningful symbol for the operation.
QuerySet.explain()
now supports the generic_plan
option on PostgreSQL 16+.
RowRange
now accepts positive integers for the start
argument and negative integers for the end
argument.
The new exclusion
argument of RowRange
and ValueRange
allows excluding rows, groups, and ties from the window frames.
QuerySet.order_by()
now supports ordering by annotation transforms such as JSONObject
keys and ArrayAgg
indices.
F()
and OuterRef()
expressions that output CharField
, EmailField
, SlugField
, URLField
, TextField
, or ArrayField
can now be sliced.
The new from_queryset
argument of Model.refresh_from_db()
and Model.arefresh_from_db()
allows customizing the queryset used to reload a model’s value. This can be used to lock the row before reloading or to select related objects.
The new Expression.constraint_validation_compatible
attribute allows specifying that the expression should be ignored during a constraint validation.
Custom tags may now set extra data on the Parser
object that will later be made available on the Template
instance. Such data may be used, for example, by the template loader, or other template clients.
Template engines now implement a check()
method that is already registered with the check framework.
assertContains()
, assertNotContains()
, and assertInHTML()
assertions now add haystacks to assertion error messages.
The RequestFactory
, AsyncRequestFactory
, Client
, and AsyncClient
classes now support the query_params
parameter, which accepts a dictionary of query string keys and values. This allows setting query strings on any HTTP methods more easily.
self**.**client**.**post("/items/1", query_params**=**{"action": "delete"}) **await** self**.**async_client**.**post("/items/1", query_params**=**{"action": "delete"})
The new SimpleTestCase.assertNotInHTML()
assertion allows testing that an HTML fragment is not contained in the given HTML haystack.
In order to enforce test isolation, database connections inside threads are no longer allowed in SimpleTestCase
.
The new DomainNameValidator
validates domain names, including internationalized domain names. The new validate_domain_name()
function returns an instance of DomainNameValidator
.
Hello! My name is Jatin Yadav and I enjoy creating websites I completed my graduation on june ,2018 and I want to be a professional web developer. The word which
Read More >