Search code examples
djangomultilingual

Django site with 2 languages


I want to develop a site with 2 languages, a default one, my native language and an optional English. I plan to have my domains as such:

www.mydomain.example/tr/
www.mydomain.example/en/

By default, once a user enter mydomain.example. they will be redirected to /tr/ version and select to go to the /en/ if they want via a top menu. And here is my question.

What is the best Django way to maintain both languages, please note that I don't want automatic translation but I want to maintain texts for both languages myself.


Solution

  • As I see it, you have two main options here:

    (1) You can keep two separate copies of the site as different Django apps and simply have your urlconf point to those apps-- so url(r'^/en/', include(myproject.en)) would be in your urlconf to point to your English app, and the other for the other language. This would involve maintaining different sets of urlconfs and different html templates, etc for the two apps, which could be useful if you're interested in having the URLs themselves also reflect the different languages (eg Spanish "/pagina/uno" vs English "/page/one").

    (2) You record the language preference in a cookie (which you should really do anyway) using Django sessions, and then have the template deliver the appropriate version of the text however you like from that cookie. The code for this could be:

    # views.py
    
    # default to your native language
    request.session['lang'] = 'tr'
    
    # someone clicks the link to change to English
    def switch_to_English_link(request):
        request.session['lang'] = 'en'
    

    And then in the templates, to gather this information, you'd use:

    <!-- my_django_template.html -->
    <div>
      <span>
         {% if request.session.lang == "en" %}
            This is my text in English!
         {% else %}
            Şimdi benim sitede Türk var!
         {% endif %}
      </span>
    </div>