Natim
Natim

Reputation: 18102

Django URL Translation - Stay on the same page when changing language

I developped a Django app with i18n for urls as well.

That look really nice but when changing the language I would like to stay on the same/previous page.

What is the best way of doing that ?

Basically to get the new url I need to do a reverse on the name of the previous page after having changed the language and do a redirect but how can I know the url name of the previous page?

Edit:

A solution that came from a collegue:

Calculate a next parameter for each language using request.resolver_match. For each language : activate(language) + reverse('{app_name}:{url_name}', args, kwargs) using request.resolver_match elements

Do you see a better idea?

Upvotes: 1

Views: 2497

Answers (2)

Ovezdurdy
Ovezdurdy

Reputation: 61

After change language with django-modeltranslation redirecting to home ?

If you want to redirect to the same page, you can replace this part of code:

{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
<div class="languages">
<p>{% trans "Language" %}: </p>
  <ul class="languages">
    {% for language in languages %}
      <li>
        <a href="/{{ language.code }}/
          {% if language.code == LANGUAGE_CODE %} class="selected"{% endif %}>
          {{ language.name_local }}
        </a>
      </li>
    {% endfor %}
  </ul>
</div>

to:

{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
<div class="languages">
<p>{% trans "Language" %}: </p>
  <ul class="languages">
    {% for language in languages %}
      <li>
        <a href="/{{ language.code }}/{{request.get_full_path|slice:"4:"}}"
          {% if language.code == LANGUAGE_CODE %} class="selected"{% endif %}>
          {{ language.name_local }}
        </a>
      </li>
    {% endfor %}
  </ul>
</div>

Attention please:

<a href="/{{ language.code }}/

replaced to <a href="/{{ language.code }}/{{request.get_full_path|slice:"4:"}}"

Upvotes: 5

rockingskier
rockingskier

Reputation: 9346

Two options for you:

Option 1

If you use the form from the documentation then will take you which brings you back to the page you were on.

Option 2

When changing the language you could use the referrer header, HTTP_REFERER , and redirect back to where you came from

# Change the language
# ... code ...

# Redirect back to where we came from
redirect_to = request.META.get('HTTP_REFERER', reverse('default-redirect-page'))
return HttpResponseRedirect(redirect_to)

Upvotes: 0

Related Questions