django i18n_patterns hide default lang_code from url

后端 未结 5 1943
旧时难觅i
旧时难觅i 2020-12-13 22:38

I\'m using the i18n_patterns to add a prefix of current lang_code to my url.

urlpatterns += i18n_patterns(\'\',
    url(r\'^\', include(\'blaszczakphoto2.gal         


        
5条回答
  •  时光说笑
    2020-12-13 23:03

    This is my solution:

    Create django middleware: django_app/lib/middleware/locale.py

    from django.utils import translation
    
        class SwitchLanguageMiddleware(object):
    
            def process_request(self, request):
                lang = request.GET.get('lang', '')
    
                if lang:
                    translation.activate(lang)
                    request.LANGUAGE_CODE = translation.get_language()
    
            def process_response(self, request, response):
                request.session['django_language'] = translation.get_language()
                if 'Content-Language' not in response:
                    response['Content-Language'] = translation.get_language()
                translation.deactivate()
    
                return response
    

    It's read the get parameter of request and if it has lang attribute, then switching language. Ex.: /about-us/?lang=pl

    Include this middleware to settings.py:

    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.locale.LocaleMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.common.CommonMiddleware',
    
        'django_app.libs.middleware.locale.SwitchLanguageMiddleware',
    )
    

提交回复
热议问题