From 7090cbbb461f0565384e1f56fd583ffc1aecf23b Mon Sep 17 00:00:00 2001 From: Martin Mayer Date: Sun, 4 Aug 2024 13:34:16 +0200 Subject: [PATCH] 16995 Move language handling to Middleware --- netbox/account/views.py | 4 ---- netbox/netbox/middleware.py | 23 +++++++++++++++++++++-- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/netbox/account/views.py b/netbox/account/views.py index 05f40df3f..d90397b8c 100644 --- a/netbox/account/views.py +++ b/netbox/account/views.py @@ -121,10 +121,6 @@ class LoginView(View): response = self.redirect_to_next(request, logger) - # Set the user's preferred language (if any) - if language := request.user.config.get('locale.language'): - response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language, max_age=request.session.get_expiry_age()) - return response else: diff --git a/netbox/netbox/middleware.py b/netbox/netbox/middleware.py index 8012965a4..7d3756f08 100644 --- a/netbox/netbox/middleware.py +++ b/netbox/netbox/middleware.py @@ -8,6 +8,7 @@ from django.core.exceptions import ImproperlyConfigured from django.db import connection, ProgrammingError from django.db.utils import InternalError from django.http import Http404, HttpResponseRedirect +from django.utils import translation from netbox.config import clear_config, get_config from netbox.context_managers import event_tracking @@ -32,12 +33,30 @@ class CoreMiddleware: # Assign a random unique ID to the request. This will be used for change logging. request.id = uuid.uuid4() + # Check if the language should be activated before the language cookie has been set. + # This will happen for instance on the first request after login. + # The language will have been already activated by the framework if the cookie exists. + if ( + request.user.is_authenticated and + settings.LANGUAGE_COOKIE_NAME not in request.COOKIES and + hasattr(request.user, 'config') + ): + if language := request.user.config.get('locale.language'): + translation.activate(language) + # Enable the event_tracking context manager and process the request. with event_tracking(request): response = self.get_response(request) - # Check if language cookie should be renewed - if request.user.is_authenticated and settings.SESSION_SAVE_EVERY_REQUEST: + # Check if language cookie should be renewed (persistent logins) or set when it does not exist, yet + if ( + request.user.is_authenticated and + hasattr(request.user, 'config') and + ( + settings.SESSION_SAVE_EVERY_REQUEST or + settings.LANGUAGE_COOKIE_NAME not in request.COOKIES + ) + ): if language := request.user.config.get('locale.language'): response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language, max_age=request.session.get_expiry_age())