How to explicitly set django_language in django session

前端 未结 3 1131
有刺的猬
有刺的猬 2020-12-23 22:27

How to explicitly set django_language in Django session?

Thanks a lot...

相关标签:
3条回答
  • 2020-12-23 22:57

    And if you will use a version >= Django 1.8. Here it is how we could use that:

    from django.utils.translation import LANGUAGE_SESSION_KEY
    
    def someview (request):
        ...
        request.session[LANGUAGE_SESSION_KEY] = 'en'
    
    0 讨论(0)
  • 2020-12-23 23:10

    If you want your users to be able to specify language, make sure that LocaleMiddleware is enabled:

    MIDDLEWARE_CLASSES = (
       ...
       'django.middleware.locale.LocaleMiddleware',
       ...
    )
    

    Then Django will look for the user's language preference in that order (see get_language_from_request in trans_real.py):

    1. in request.path_info, if i18n_patterns are used;
    2. request.session[settings.LANGUAGE_SESSION_KEY];
    3. request.COOKIES[settings.LANGUAGE_COOKIE_NAME];
    4. every language in request.META['HTTP_ACCEPT_LANGUAGE'], until accepted one is found;
    5. settings.LANGUAGE_CODE.

    So the most straightforward way to set language explicitly in Django session is to rewrite request.session[settings.LANGUAGE_SESSION_KEY]:

    def someview (request):
        ...
        request.session[settings.LANGUAGE_SESSION_KEY] = 'en'
        ...
    
    0 讨论(0)
  • 2020-12-23 23:12

    Consider using django.views.i18n.set_language(). Activate this view by adding the following line to your URLconf:

    # This example makes the view available at /i18n/setlang/
    url(r'^i18n/', include('django.conf.urls.i18n')),
    

    As a convenience, Django comes with a view, django.views.i18n.set_language(), that sets a user’s language preference and redirects to a given URL or, by default, back to the previous page.

    The view expects to be called via the POST method, with a language parameter set in request. If session support is enabled, the view saves the language choice in the user’s session. Otherwise, it saves the language choice in a cookie that is by default named django_language. (The name can be changed through the LANGUAGE_COOKIE_NAME setting.)

    0 讨论(0)
提交回复
热议问题