Overview
Django 1.2, released on May 17, 2010, brings multi-database support and strengthens CSRF protection. This version allows reading and writing to multiple databases within the same project, a highly requested community feature.
Key Features
Multi-database support
Django 1.2 allows configuring and using multiple databases simultaneously. A database router directs reads and writes to the correct database based on the model or application.
python
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'main_app',
},
'analytics': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'analytics_app',
},
}
# Database router
class AnalyticsRouter:
def db_for_read(self, model, **hints):
if model._meta.app_label == 'analytics':
return 'analytics'
return 'default'
def db_for_write(self, model, **hints):
if model._meta.app_label == 'analytics':
return 'analytics'
return 'default'
# Explicit query on a specific database
stats = Visit.objects.using('analytics').filter(page='/home/').count()
CSRF protection improvements
CSRF (Cross-Site Request Forgery) protection is now enabled by default via a middleware. The {% csrf_token %} template tag automatically generates the protection token.
python
# In the HTML template
# <form method="post">
# {% csrf_token %}
# <input type="text" name="title">
# <button type="submit">Submit</button>
# </form>
# In the view: verification is automatic
from django.shortcuts import render, redirect
def create_article(request):
if request.method == 'POST':
# The CSRF middleware has already verified the token
title = request.POST['title']
Article.objects.create(title=title, author=request.user)
return redirect('article_list')
return render(request, 'blog/create.html')
