djangodjango-multilingual

Issues with multiple languages


I want my app will be available in multiple languages (let say two,one is default english and one more).

And these both options available in my home page and there must be a link shown which makes user able to select his choice of language.

I am reading the Django official documentation for this

so any one can let me know the general idea how I can do that.

and one more thing......in settings.py there is default LANGUAGE_CODE = 'en-us' given,BUT as I want my app in more then one language so How i can specify that country code here.

like this works LANGUAGE_CODE = 'en-us','es-MX (Spanish)' or I have to do it in some way.

And what is the purpose of this .po extension in this.


Solution

  • settings.py

    LANGUAGE_CODE='en_us'
    gettext = lambda s: s
    LANGUAGES = (
        ('en', gettext('English')),
        ('de', gettext('German')),
    )
    
    MIDDLEWARE_CLASSES = (
        ...
        'lang.SessionBasedLocaleMiddleware',
    )
    

    lang.py

    from django.conf import settings
    
    from django.utils.cache import patch_vary_headers
    from django.utils import translation
    
    class SessionBasedLocaleMiddleware(object):
        """
        This Middleware saves the desired content language in the user session.
        The SessionMiddleware has to be activated.
        """
        def process_request(self, request):
            if request.method == 'GET' and 'lang' in request.GET:
                    language = request.GET['lang']
                    request.session['language'] = language
            elif 'language' in request.session:
                    language = request.session['language']
            else:
                    language = translation.get_language_from_request(request)
    
            for lang in settings.LANGUAGES:
                if lang[0] == language:
                    translation.activate(language)
    
            request.LANGUAGE_CODE = translation.get_language()
    
        def process_response(self, request, response):
            patch_vary_headers(response, ('Accept-Language',))
            if 'Content-Language' not in response:
                response['Content-Language'] = translation.get_language()
            translation.deactivate()
            return response
    

    Access different languages http://example.com/?lang=de

    And finaly let django create your .po files. Heres the documentation for that.