Skip to content

Instantly share code, notes, and snippets.

@teury
Last active November 9, 2019 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teury/5d2213181ed0abe06c316c19431f355e to your computer and use it in GitHub Desktop.
Save teury/5d2213181ed0abe06c316c19431f355e to your computer and use it in GitHub Desktop.
Django Middleware language change query string ?hl=langcode
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
@teury
Copy link
Author

teury commented Nov 9, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment