Last active
November 9, 2019 23:40
-
-
Save teury/5d2213181ed0abe06c316c19431f355e to your computer and use it in GitHub Desktop.
Django Middleware language change query string ?hl=langcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import django | |
from django.utils import translation | |
from django.shortcuts import redirect, reverse | |
def is_django_greater_than_1_10(): | |
main_version = django.VERSION[0] | |
if main_version > 1: | |
return True | |
sub_version = django.VERSION[1] | |
if main_version == 1 and sub_version >= 10: | |
return True | |
return False | |
if is_django_greater_than_1_10(): | |
from django.utils.deprecation import MiddlewareMixin | |
superclass = MiddlewareMixin | |
else: | |
superclass = object | |
class LanguageMiddleware(superclass): | |
def process_response(self, request, response): | |
if request.resolver_match.view_name is "home": | |
lang_url = request.GET.get('hl') | |
if not lang_url: | |
return response | |
current_language = translation.get_language() | |
if lang_url == current_language: | |
return response | |
translation.activate(lang_url) | |
request.session[translation.LANGUAGE_SESSION_KEY] = lang_url | |
return redirect(reverse('home') + '?hl=' + lang_url) | |
else: | |
return response | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have implemented this system in a single "home" url
change the language according to the key value
Traslate by Google.
Idioma nativo = Español