Search code examples
pythondjangourl-routingmultilingual

Multilanguage URLs in Django


What is the best way to support multilanguage URLs in Django? Like:

http://myenglishwebsite.com/user/foo
http://mygermanwebsite.com/benutzer/foo

Should I use multilang in urls.py like:

(r'^%s/(?P<slug>[-w]+)/$' % _('user'), 'myapp.view.relatedaction')

It doesn't seem like a good solution and I couldn't make it work :))


Solution

  • This solution doesn't work because urls.py file is loading once in Django server before first user actually can make any request, so it must be user-independent file (any module level code should be user-independent, because it is loading only once).

    My guess is that Django url resolver makes str() casting somewhere in the middle of the request, so you can use some decorator class:

    (URLLangDecorator(r'^%s/(?P<slug>[-w]+)/$', ['user']), 'myapp.view.relatedaction')
    class URLLangDecorator:
        def __init__(self, url, params):
            self.url, self.params = url, params
    
        def __str__(self):
            return self.url % map(_, self.params)
        # Django can also preform "%" operation, so to be safe:
        def __mod__(self, arg):
            return str(self) % arg
    

    This is guess, so I'm not sure if it will work.