0

I have a requirement where in I have to write this url www.example.com/something/something/ to www.example.com/en/something/something/ only when user chooses English language.

This is for an existing site already done in django with urls for the normal part done. Now if user chooses english language, I must rewrite the urls.

I thought i could manually start changing all the urls in django templates like so

{% if request.session.language == 'en' %} 
    <a href="/en/something"..>
{% else %}
    <a href="/something"..>
{% endif %}

But I have been asked not to do it that way as the number of links is too much to do it this way.

Then I thought of trying a custom middleware, where I could access the request object in process_request and do a return HttpResponsePermanentRedirect(redirect_url)

But it seems process_request processes all the requests one by one, including the images and other links. But what I want is the first request, the actual url that was requested.

So I tried the same in a constructor in the middleware hoping it would get called only once and that would be the first request. But the problem I face is that __init__ accepts only self and **args and not a request object, so I cannot access the session variables there.

I thought about trying this in apache, but I need to do the url redirect only if user selects the English language, not always.

4

1 回答 1

2

一旦您从文档中阅读了 django urls 模式中的国际化,您就会意识到它是一个简单的过程。

  1. 更新您的urls.py

    from django.conf.urls.i18n import i18n_patterns
    
    urlpatterns += i18n_patterns('',
        url(r'^something/$', 'something.view', name='something'),
        # other urls like you would normally have
    )
    
  2. 确保django.middleware.locale.LocaleMiddleware在您MIDDLEWARE_CLASSESsettings.py.

而已。现在,您的模式将根据用户选择的语言进行更新。

于 2013-03-06T07:04:57.223 回答