How do I set urlpatterns based on domain name or TLD, in Django?
For some links, Amazon shows url in native language based on its website tld.
http://www.amazon.de/bücher-buch-literatur/ ( de : books => bücher )
http://www.amazon.fr/Nouveautés-paraître-Livres/ ( fr : books => Livres )
http://www.amazon.co.jp/和書-ユーズドブッ-英語学習/ ( jp : books => 和書 )
( the links are incomplete and just show as samples. )
Is it possible to get host name in urls.py? (request object is not available in urls.py) or maybe in process_request of middleware and use it in urls.py(how???)
Any alternate suggestions how to achive this?
#---------- pseudocode ---------- website_tld = get_host(request).split('.')[-1] #.fr French : Books : Livres #.de German : Books : Bücher if website_tld == 'fr': lang_word = 'Livres' elif website_tld == 'de': lang_word = 'Bücher' else: lang_word = 'books' urlpatterns = patterns('', url(r'^%s/$' % lang_word,books_view, name='books'), )
The url pattern needs to be built based on tld and later in the template, <a href='{% url books %}' >{% trans 'books' %}</a> to render html as <a href='Bücher'>Bücher</a> or <a href='Livres'>Livres</a>
You have to do this at the webserver level (for example using mod_rewrite in Apache) or with middleware (for example this snippet)Also see this SO question
Update: after your comment I thought about it some more. I liked Carl Meyer’s answer, but then realized it wouldn’t handle {% url %} reversing properly. So here’s what I would do:
Multiple sites: You need to use the Django sites framework. Which means making site instances for each language using the Django admin.
Multiple settings: Each language site will also have its own settings.py. The only differences between each site will be the
SITE_IDandROOT_URLCONFsettings so, to follow DRY principle, you should keep the common settings in a different file and import them into the master file like this:… and so on.
Multiple URL conf: As implied above, a url conf for each site:
… and so on.
This way the url name (in this example ‘books’) is the same for all languages, and therefore
{% url books %}will reverse properly and the domain name will be the domain_name field of the Site object withSITE_ID.Multiple web server instances: In order for each SITE to work properly they each need their own server instances. For apache + mod_wsgi this means a different wsgi application for each SITE like this:
… and so on along with matching apache virtual host for each site:
Hopefully this is clear 🙂