How can I save the language chosen by the user?

How can I save the language chosen by the user?

I have allowed many languages on the site. But I want to know what language the user is using.

The reason why I need such a thing is that I send an automatic message to the user by the system, but since I do not know the language selected by the user, the message is sent in the default language.

What is the most practical method in this regard? I couldn’t find much information.

I found this but it doesn’t work.

Thank you.

Where is this being chosen? After the user chooses a language, you’ll need to save that to the database. Have you already managed to save the selected language into the database?

Maybe you’re not activating the “language” that the user has chosen. Where are you sending this message?

When posting code here, wrap it with backticks `

Thank you for your answer.

At the moment I don’t save the user’s language selection anywhere. I use the html codes given by django when choosing the user language. With the process here, the user’s language is detected by the browser. I want to ensure that the language selected by the user is also detected by the system.

Django language selection menu

  <!--Language Start-->
    <li class="nav-item">
      {% get_current_language as LANGUAGE_CODE %}
      {% get_available_languages as LANGUAGES %}
      {% get_language_info_list for LANGUAGES as languages %}

      <div class="dropdown me-2 mt-2">
        <a id="navbarDropdownLang" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          <div id="showLanguage" class="avatar avatar-xl">
            <div class="avatar-name rounded-circle bg-300 text-dark">
              <span class="text-uppercase">{{LANGUAGE_CODE}}</span>
            </div>
            
        </div>
        </a>
        <div class="dropdown-menu dropdown-caret dropdown-caret dropdown-menu-end py-0" aria-labelledby="navbarDropdownLang">
          <div class="bg-white dark__bg-1000 rounded-2 py-2">

            <!--Language Options-->
            {% for lang in languages %}
            <a href="/{{ lang.code }}/{{request.get_full_path|slice:'4:'}}" class="cursor-pointer text-decoration-none" id="warehouseSelect">
              <button class="text-center dropdown-item {% if LANGUAGE_CODE == lang.code %} text-dark {%endif%}" type="button">                 
                  {{ lang.name }} 
              </button>
            </a>
            {% endfor %}
          </div>

        </div>
      </div>
    </li>

I’m not entirely sure how this process should be.

1- So here, when the user makes a language choice on the html side, Should I save the chosen language at this time? For example like this:

<script>
        $('#warehouseSelect').click(function(){
            $.ajax({
                type:'GET',
                url: "{% url 'user_language_selected' %}",
                success: function(res){
                    alert("Language Saved");
                },
                error: function(){
                    alert("an unknown error occurred");
                }
            });
        })
    </script>

2- When the user makes a selection on the html side, does django save the selection somewhere?

3- Should I write on the model which language the user has selected during each request with middleware?

model.py

class Account(AbstractBaseUser, PermissionsMixin): 
    interface_language = models.CharField(max_length=10, blank=True)

language_middleware.py

from django.utils import translation


def language_middleware_save(get_response):
    def middleware(request):
        if 'staffboard' not in request.path_info: 
            user = getattr(request, 'user', None)
            if user is not None and user.is_authenticated:
                cur_language = translation.get_language()
                user.interface_language = cur_language
                user.save()
            response = get_response(request)
            return response
    return middleware

I’m not sure how this should be done.

You have some options, if the language choice is temporary, then you can save that on the session. If is not temporary, and you have an authenticated user, you can save that on your user model, or create another model with a foreignkey to the user model.
Opinion: It’s better to just add a column to the user model in this case.

No, that information is “stored” only at URL. To save this information, you can send the selected language to a view that will save the selected language to the user model or the other model that you created. So you’re going to need to POST this to a view and save this information.

When you have the preferred_language binded to a user you can then use this information. If you’re going to need this very specific to a view, then you need to call django.utils.translation.activate with the user.preferred_language argument.
But if you plan to use this application-wide, i would write a middleware that verifies if the user is_authenticated, and if so, call the activate function to the user preferred language.

1 Like

I guess I’ll go with the first option. Thank you very much.

1 Like