How to maintain the selected language in a dropdown menu in Django even after the page

I'm currently working on a language switcher form for my website which supports 3 languages. Everything is functional except that when the page reloads, the content changes to the new language but the selected option from the dropdown reverts back to the default language. I'm looking for a solution to persist the selected language after the page reloads. Any tips or suggestions would be greatly 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>

Answer №1

To utilize the LANGUAGE_CODE variable within templates, you must first load the i18n module.

Add this code snippet at the beginning of your HTML template:

{% load i18n %}

Additionally, ensure that the i18n module is enabled in your settings and 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',
                # ...
            ],
        },
    },
]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery to dynamically add one of two fields to a form

After successfully using JQuery to add a field to a form, I am now stuck on how to implement two add field buttons for adding different fields. Can anyone point me in the right direction? <html> <head> <title>jQuery add / remove textb ...

What is the best way to update the variable value in cleaned_data?

I am looking for a way to save a photo with a watermark directly applied to it. Currently, the code grabs a photo from a form, adds a watermark, but saves it as a separate file. I want the photo submitted in the form to be processed and saved with the wa ...

Display a CSS animation upon hovering the mouse

I'm looking to create a unique animation that involves drawing angled and straight lines, along with displaying text from left to right upon hovering over a button. I am relatively new to this concept and would appreciate any guidance. Additionally, I ...

Implement a toggle feature for login and registration with jQuery

I am facing an issue with the show/hide model on my website. When I click the link associated with it, nothing happens. I want it to function in a way that when I click "Sign up," the register form is displayed and when I click "Login," the register form ...

Using conditional links in Django templates

Looking for a more concise way to write the following Django template code? {% if condition %} <a href="{% url 'url_name' arg1 arg2 kwarg='some value' %}"> {# just some block of code #} <h2>{{ value|capfirst }}< ...

Transition smoothly between HTML pages by using a script to fade in and out while changing images from an array

I am facing a small issue. I have successfully implemented a fadeIn and fadeOut effect on an entire page by clicking HTML links. However, I now want to dynamically change the images associated with these links using an array. Here is the code for transiti ...

The margins are misaligned on a tablet-sized device due to an issue with the media

Why are the margins not maintained well when media queries are applied for tablet view, i.e., medium-sized devices? The third block is coded to acquire 100% width in medium size but the margins do not align well. What could be causing the third paragraph t ...

The functionality of the button seems to be malfunctioning specifically in the Mac Firefox

My button isn't working in Mac Firefox only. Below is the code: <button class="col btn-change"><a href="/p/88" style="color: white;">Landscape</a></button> However, the following two codes are functioning correctly. In the fi ...

Basic Timer with Visual Background

Struggling to find the right CSS/script for a straightforward countdown timer, Here are the requirements: Countdown in days only, no need for hours, minutes, and seconds Ability to use a custom image as background I've scoured online searches but n ...

Guide on inserting an item into a vertical navigation menu

When it comes to creating a vertical menu, I rely on Bootstrap 5. https://i.sstatic.net/8CWYK.png The issue I'm facing is how to add a black background to the top of the left menu. https://i.sstatic.net/yoEcO.png I am unsure whether I should imple ...

Deactivate toggle effect by clicking on a different link

My existing JavaScript code changes the background color of a link when it is clicked: $(".button").click(function(){ $(this).css('background-color', '#555'); }); While this functionality works, I am looking to have the color tog ...

After upgrading to version 1.5, Django started displaying the error message "current transaction is aborted, commands ignored until end of transaction block"

Since upgrading to Django 1.5, I've encountered a strange bug. When accessing my ClientDetailView with Django debug toolbar enabled, I receive the following error: Traceback: File "/Users/mirkocrocop/.virtualenvs/upstream_backend/lib/python2.7/site-p ...

What is causing Django to disregard my custom encoder class?

In my coding project, I have created two classes called Website and WordpressWebsite. The class WordpressWebsite is a subclass of Website. During the process of encoding an instance of WordpressWebsite into JSON, only the attributes specific to Wordpress ...

How come the Bootstrap 4 column is not utilizing its entire available width?

My webpage is structured as follows: <div class="container"> <div class="row mb-5"> <div class="col-12 col-md-3"> <img class="mr-5 img-fluid" src="big_icon_1.png" alt="Big icon 1"> </div> <div class-"co ...

Flexbox allows all elements to fall in line in a single row

I'm trying to create a basic counter program. I have placed the label and buttons inside a div container and used flexbox styling on them. However, despite setting the display of the label to block and adding a line break after it, the buttons and lab ...

Determine the number of Django query set results based on a specific attribute after applying

Is there a straightforward method within Django to execute a queryset in which I can perform statistical analysis based on a specific attribute from the output? After reading through this article and conducting some initial tests, it appears that using th ...

Dynamic page changes can be achieved by using JavaScript within HTML, even when the input is

When I click the register button and the input fields appear, the problem arises. When I fill in the fields and then the code jumps to the function $ (document) .on ("click", "#register_in", function (), all $().val(), it results in all values being undefi ...

Building a custom form layout using Bootstrap v4 with three input fields and a button all lined up on one

I am struggling to create a form with 3 input fields and a button on the same row using Bootstrap v4 for the design. Can anyone help me figure this out? Take a look at my current design: Click here My Code <div class="col-sm-7 mx-auto bg-faded"&g ...

Should we make it a routine to include shared sass variables in each vue component for better practice?

Within my Vue application, there are numerous components that rely on shared variables like colors. I'm considering having each component import a global "variables.scss" file. Would this approach have any adverse effects? ...

What is the best way to remove this .click function?

My goal is to create a switch function where clicking the "on" button changes its CSS, and if the user then clicks on the "off" button, the CSS returns to normal. I also need the switch to default to the "on" position, but my attempts so far have been unsu ...