Search code examples
djangointernationalizationurl-pattern

Check if current URL pattern exist in another language in Django


I'm trying to start of my new website in Django with a lot of settings which down the road will be tougher to implement. One of these things is website internationalization, but also url pattern internationalization.

What I am trying to achieve is having urls like this:

www.example.com/news                 [en] [news]
www.example.com/en/news              [en] [news]
www.example.com/no/nyheter           [no] [news]
www.example.com/en/top-articles      [en] [top articles]

and on every page I visit, I want the website navigation to have a dropdown menu, which contains website languages, and which language is currently selected. Similar to this:

<ul class="dropdown">
    <li><a href="/en/news" hreflang="en" class="active">English</a></li>
    <li><a href="/no/nyheter" hreflang="no" rel="alternate">Norsk</a></li>
</ul>

Now as for changing to another language, is there any way to see if the current page exists in the language the users can pick from?

If the current page does not exist in the language of choice, I want the user to be returned to the frontpage of the selected language. So the dropdown would look like this:

<ul class="dropdown">
    <li><a href="/en/top-articles" hreflang="en" class="active">English</a></li>
    <li><a href="/no" hreflang="no">Norsk</a></li>
</ul>

Solution

  • One way I see you doing this is by setting django_language in the user session based on user selection.

    Django will handle translation of any text that is specified using gettext_lazy. Your URLs will be generated using Django url.reverse function together with django_language and other arguments.

    Determining if the current page exists in the language the users can pick from will boil down to your implementation.

    For example, content models will have a language field make it easy to query for records whose language match django_language. If there is no match, a redirect can be made to language front page assuming that will always exist.

    References:

    http://django-book.readthedocs.io/en/latest/chapter19.html