Language Switcher in Templates

A snippet showing how to add a language switcher in templates.


<!-- templates/language_switcher.html -->

{% load i18n %}
<form action="{% url 'set_language' %}" method="post" class="d-inline">
  {% csrf_token %}
  <input name="next" type="hidden" value="{{ redirect_to }}">
  <select name="language" class="form-select d-inline w-auto">
    {% get_current_language as LANGUAGE_CODE %}
    {% get_available_languages as LANGUAGES %}
    {% for code, name in LANGUAGES %}
      <option value="{{ code }}"{% if code == LANGUAGE_CODE %} selected{% endif %}>
        {{ name }}
      </option>
    {% endfor %}
  </select>
  <button type="submit" class="btn btn-outline-primary ms-2">{% trans "Change" %}</button>
</form>
      

# urls.py

from django.urls import path, include

urlpatterns = [
    path("i18n/", include("django.conf.urls.i18n")),  # provides 'set_language' view
]
      
Explanation:
  • Include django.conf.urls.i18n to expose the set_language endpoint.
  • Use {% url 'set_language' %} to reverse the URL and include the next parameter.
Previous snippet
Activate Language in Views
Next snippet
Set Default Language
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.