Login

I18n URLs via Middleware

Author:
zerok
Posted:
August 17, 2007
Language:
Python
Version:
.96
Score:
6 (after 6 ratings)

This is an example middleware that is highly inspired by how Symfony handles i18n in URLs. You basically set a (?P<dj_culture>[\w-]+) pattern in your URL and this middleware will determine the language to use for the i18n toolkit for Django.

It also removes the dj_culture parameter after dealing with it, so that you don't have to change all the views you want this middleware to work with.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
### Middleware
from django.conf import settings
from django.utils import translation
from django.http import Http404

class I18nUrlsMiddleware(object):
	"""
	This is a very simple middleware that checks if the view being requested
	is about to receive a "dj_culture" parameter. If this is the case, this 
	middleware removes this argument and uses it to initialize Django's
	i18n system with the requested culture if it is one of the supported
	cultures.
	"""
	
	def handle_culture(self,request,culture):
		translation.activate(culture)
		request.LANGUAGE_CODE = translation.get_language()
	
	def process_view(self, request, view_func, view_args, view_kwargs):
		culture = view_kwargs.get('dj_culture',None)
		if culture:
			ret = None
			if culture in settings.CULTURES:
				ret = self.handle_culture(request,culture)
			else:
				# Fallback for the lazy of us who prefer to keep things simple.
				pcult = culture.split('-')[0]
				if pcult in settings.CULTURES:
					ret = self.handle_culture(request,pcult)
				else:
					raise Http404
			# Remove the culture parameter again so that we can use all our
			# old views.
			del(view_kwargs['dj_culture'])
			return ret

### URLs
from django.conf.urls.defaults import *

urlpatterns = patterns('',
	(r'(?P<dj_culture>[\w-]+)/','views.index'),
)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 4 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

jefurii (on January 8, 2008):

Very useful snippet - Django's handling of i18n is great, but sometimes it's nice to be able to specify the language code in the URL.

#

Please login first before commenting.