[Django]-Implementing Django language selection form as buttons

4πŸ‘

βœ…

The following is a method creating each language as its own hidden form with a submit button that can be styled with css.

If you would like the active language to be styled differently, you could use a django if statement to change the css if it is the current language.

{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}

{% for language in languages %}
  <form action="{% url 'set_language' %}" method="post" id="form_{{ language.code }}" style="display:inline!important;">
  {% csrf_token %}
    <input name="next" type="hidden" value="{{ redirect_to }}" />
    <input name="language" type="hidden" value="{{ language.code }}" />
  </form>
  <button class="lang-button" type="submit" form="form_{{ language.code }}" value="Submit">[{{ language.code }}]</button>
{% endfor %}
πŸ‘€ryanjdillon

1πŸ‘

You can also put all buttons in one form:

{% load i18n %}

<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
  <input name="next" type="hidden" value="{{ redirect_to }}">
  {% get_current_language as LANGUAGE_CODE %}
  {% get_available_languages as LANGUAGES %}
  {% get_language_info_list for LANGUAGES as languages %}
  {% for language in languages %}
    <button name="language" value="{{ language.code }}" type="submit">{{ language.code }}</button>
  {% endfor %}
</form>

Leave a comment