Search code examples
cssdjangoformsdropdownreload

Django keep dropdown selected language after page reload


I have a form to change languages (3 languages so far) and it works except that when the page reloads, the content changes to the new language but the selected option from the dropdown is lost (instead shows default language). How can I keep the selected language after page reload? Any help is appreciated

 <form action="{% url 'set_language' %}" method="POST">
            {% csrf_token %}
            <input type="hidden" id="languageSwitcher" name="selected" value="{{ redirect_to}}">
            <select name ="language" id="languageField">
              {% get_available_languages as LANGUAGES %}
              {% get_language_info_list for LANGUAGES as languages %}
              {% for language in languages%}
              <option  value="{{language.code}}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}>
                {{language.name_local}} 
              </option>
              {% endfor %}
            </select>
          <input type="submit" id ="languageSwitcher" value="Change">
          </form>

Solution

  • To use the LANGUAGE_CODE variable in templates, you have to load i18n first.

    Put this line of code at the top of your html template:

    {% load i18n %}
    

    Also, make sure i18n is enabled in your settings & context processors:

    USE_I18N = True
    # ...
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    # ...
                    'django.template.context_processors.i18n',
                    # ...
                ],
            },
        },
    ]