[Django]-Set language of template in Django by clicking on <a> link from Bootstrap Dropdown menu

7👍

This is what works for me: adding an additional input element with the name “language”

Further, assign a language code for it in JS before submitting the form, i.e. document..language.value =

Then the part of template looks like this:

<form name="ui" action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
<input name="language" type="hidden"/>
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
{% get_current_language as LANGUAGE_CODE %}
{% get_language_info for LANGUAGE_CODE as lang %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{{ lang.name_local }}
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
{% for language in languages %}
    <li><a href="#" onclick="document.ui.language.value='{{ language.code}}'; document.ui.submit();">{{ language.name_local }}</a></li>                                                                    
{% endfor %}
</ul>

👤Max Li

4👍

you can try this easier one:

{% load i18n %}
{% get_available_languages as languages %}

{% for language in languages %}
    <li class="{% ifequal current_language language.0 %}active{% endifequal %}">
        <a href="/./{{ language.0 }}/" title="{{ language.1 }}">
            {{ language.1 }}
        </a>
    </li>
{% endfor %}

1👍

@doniyor an slightly modified version of your answer (consider using i18n context_processor )

{% with "/"|add:LANGUAGE_CODE as redundant %}
  {% for language_code, _ in LANGUAGES %}
    {% if language_code != LANGUAGE_CODE %}
      <li>
        <a class="text-decoration-none dropdown-item archive-link"
           href="/{{ language_code }}{{ request.get_full_path|cut:redundant }}">
           {{ language_code|language_name_local }} ({{ language_code }})
        </a>
      </li>
    {% endif %}
  {% endfor %}
{% endwith %}

Leave a comment