views:

477

answers:

3

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>

+6  A: 
Van Gale
Thanks Van, Maybe I am missing the point from the other question you refer. Here, the url patterns 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>
Ingenutrix
I have updated the question to reflect this.
Ingenutrix
Van, Thanks for such a detailed writeup!
Ingenutrix
A: 

In django there's a table called "Sites". Maybe you can do something with that?

Jack Ha
+1  A: 

You can probably do this with a middleware that retrieves the TLD via request.META['HTTP_HOST'] and prepends it to request.path; then your root URLconf can switch out to language-specific URLconfs based on the TLD as the first URL path segment. Something like this (untested!):

class PrependTLDMiddleware:
""" Prepend the top level domain to the URL path so it can be switched on in 
a URLconf. """

def process_request(self, request):
    tld = request.META['HTTP_HOST'].split('.')[-1]
    request.path = "/%s%s" % (tld, request.path)

And in your URLconf:

urlpatterns = patterns('',
    url(r'^de/' include('de_urls')),
    url(r'^fr/', include('fr_urls')),
    url(r'^[^/]+/', include('en_urls'))
)

And then de_urls.py, fr_urls.py, and en_urls.py could each have all the URLs you need in the appropriate language.

Carl Meyer