Django 4.0 marks a significant release with native Redis support and continued async improvements. Python 3.8+ requirement enables modern features. At ZIRA Software, Django 4.0 powers our Python-based applications with improved caching.
Installation
# Upgrade Django
pip install Django>=4.0
# Install Redis support
pip install redis
Native Redis Cache Backend
# settings.py - Before Django 4.0 (required django-redis)
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1',
}
}
# Django 4.0+ - Built-in
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.redis.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379',
}
}
# With authentication
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.redis.RedisCache',
'LOCATION': 'redis://username:password@127.0.0.1:6379',
}
}
# Multiple Redis servers
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.redis.RedisCache',
'LOCATION': [
'redis://127.0.0.1:6379',
'redis://127.0.0.1:6380',
],
}
}
Using the Cache
from django.core.cache import cache
# Basic operations
cache.set('my_key', 'my_value', timeout=300)
value = cache.get('my_key')
# Cache with default
value = cache.get('my_key', default='fallback')
# Delete
cache.delete('my_key')
# Get or set pattern
def get_expensive_data():
return expensive_computation()
data = cache.get_or_set('expensive_key', get_expensive_data, timeout=3600)
Async Template Rendering
# views.py - Async views with templates
from django.shortcuts import render
async def dashboard(request):
# Async database queries
stats = await get_dashboard_stats()
recent_orders = await Order.objects.filter(
created_at__gte=timezone.now() - timedelta(days=7)
).acount()
return render(request, 'dashboard.html', {
'stats': stats,
'recent_orders': recent_orders,
})
# Async helper
async def get_dashboard_stats():
users = await User.objects.acount()
orders = await Order.objects.acount()
revenue = await Order.objects.aaggregate(total=Sum('amount'))
return {
'users': users,
'orders': orders,
'revenue': revenue['total'],
}
Scrypt Password Hasher
# settings.py - More secure password hashing
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.ScryptPasswordHasher', # New in 4.0
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]
Timezone Handling
# settings.py - Simplified timezone config
USE_TZ = True
TIME_ZONE = 'America/New_York'
# Deprecated USE_L10N removed - localization always enabled
# In code
from django.utils import timezone
import zoneinfo
# Using zoneinfo (Python 3.9+)
eastern = zoneinfo.ZoneInfo('America/New_York')
now_eastern = timezone.now().astimezone(eastern)
Form Rendering Improvements
# forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
# New template-based rendering
template_name = 'forms/contact.html'
template_name_label = 'forms/label.html'
<!-- templates/forms/contact.html -->
{% for field in form %}
<div class="form-group">
{{ field.label_tag }}
{{ field }}
{% if field.errors %}
<ul class="errors">
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
{% endfor %}
Model Constraints
from django.db import models
from django.db.models import Q, CheckConstraint, UniqueConstraint
class Event(models.Model):
name = models.CharField(max_length=200)
start_date = models.DateTimeField()
end_date = models.DateTimeField()
class Meta:
constraints = [
CheckConstraint(
check=Q(end_date__gt=models.F('start_date')),
name='end_after_start',
),
UniqueConstraint(
fields=['name', 'start_date'],
name='unique_event_per_date',
),
]
Conclusion
Django 4.0 with native Redis cache and async improvements modernizes Python web development. The built-in Redis backend simplifies deployment and reduces dependencies.
Building Django applications? Contact ZIRA Software for Python development services.