开发者

Django: How can I localize my urls?

How can I localize my urls in Django?

url(u'^{0}/$'.format(_('register')), RegisterView.as_view(), name='register'),

I tried the above but it only seems to work when I stop and start the server开发者_如何学运维. I guess that the urls are translated when the application start.

So if there a way to solve this?


It's a bit more complicated than just throwing _() in urls.py. You have spotted the reason yourself: The URLs are evaluated once, when Django starts, and not for every request. Therefore you will have to

a) put every possible translation in urls.py, or

b) implement routing yourself

A. All in urls.py

url('hello', hello, name="hello_en"),
url('hallo', hello, name="hello_de"),
url('buenos_dias', hello, name="hello_es"),

Obviously not a nice solution, but it works for small projects.

B. Implementing routing

That has it's own drawback, especially when it comes to use reverse(). However, it works in principle:

urls.py:

#...
url('(?<path>.+)', dispatcher),
#...

views.py:

def dispatcher(request, path):
    if path == "hallo":
        lang = "de"
    elif path == "buenos_dias":
        lang = "de"
    else:
        lang = "en"

Of course, you can make the lookup more intelligent, but then you have to make preassumptions:

# if request.session['language'] can be trusted:
def dispatcher(request, path):
    list_of_views = ['contact', 'about', 'foo']
    v = None
    for view in list_of_views:
        if _(view) == path:
            v = view
            break
    if v is None:
        # return 404 or the home page


Internationalization of URLs has been introduced in django 1.4

see https://docs.djangoproject.com/en/dev/topics/i18n/translation/#url-internationalization

this is exactly what you are looking for

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜