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.