Search code examples
pythondjangopython-2.7internationalizationdjango-i18n

Django Switch language with i18n pattern and normal url_pattern


I've to do the switch language for an app who have some urls in i18n pattern like all the pages we want to translate with prefix in order to have good SEO, and other pages which we don't want to have the prefix in the url.

So I separated the 2 patterns, till this all is all right and when I'm doing the form to handle the switch language I'm facing only problems :

This is my form :

<form action="{% url 'set_language' %}" method="POST" class="langform" style="display:none;">
{% csrf_token %}
<input name="next" type="hidden" value="{{ request.get_full_path|strip_lang }}" />
<input name="language" id="language" type="hidden" value="" />
</form>

I validate via javascript. All is fine, I fill the language value and the form is well submit. My real problem is the next value, because I need a generic next value so I did a request.path with a filter like this one :

@register.filter(name="strip_lang")
    def strip_lang(value):
        lang = get_language()
        return '/%s/' % value.lstrip('/%s/' % lang)

The goal of this filter is to watch if the url have a language prefix if yes, it remove it to have in the next value the only the url without prefix.

the output of this filter is like this : if we are at /fr/pages/default it will be /pages/default/

I click on the switch language but nothing work. It still the same language. So I removed a slash but then it's a 404 because it's not the right path...

What can I do to manage the 2 kind of urls that I've ?? One with URL prefix and one without...

The language is well activate in some of the situations.

Thank in advance!


Solution

  • Ok so I managed to make it work I just had to add {% language lang_code %} to my link.

    Now I've my urls which are working with a generic next value.

    <ul class="lang-switch">
                {% get_language_info_list for LANGUAGES as languages %}
                  {% for language in languages %}
                  {% language lang_code %}
                  <li><a href="#" rel="{{ language.code }}">{{ language.code|upper }}</a></li>
                  {% endlanguage %}
                  {% endfor %}
            </ul>
    

    I just post my little javascript which does the work to help you make it work and to understand how I manage to do this :

      $('.lang-switch li a').click(function (e) {
    e.preventDefault;
    var lang = $(this).attr('rel');
    $('.langform #language').val(lang);
    $('.langform').submit();
    });