Change language and its url in django

I have a dual language site in Django and a Select form to change the site language. It worked fine until I started using i18n_patterns

in urls. So now every URL on my site starts with: foo.com/en/

or foo.com/es/

.

The problem is that when I change the language using the form, the url parameter overrides the form selection so the language doesn't change. The only way to achieve this is to do it manually from the URL.

But I don't want to associate all language changes with the start page. The url could be something like foo.com/en/post/foo-post/

and I would like to be able to change it to foo.com/es/post/foo-post/

. What am I doing wrong?

My form:

<form action="{% url 'set_language' %}" method="post">
    {% csrf_token %}
    <input name="next" type="hidden" value="{{ redirect_to }}" />
    <select name="language"  onchange="this.form.submit()">
        <option value="es" {% if LANGUAGE_CODE == "es" %} selected="selected"{% endif %}>Español</option>
        <option value="eu"  {% if LANGUAGE_CODE == "en" %} selected="selected"{% endif %}>English</option>
    </select>
</form>

      

Many thanks

+3


source to share


1 answer


I have a webpage with multilanguage selection, here is an example from my base.html template. I hope you find it helpful.



{% load i18n %}
{% get_current_language as CURRENT_LANGUAGE %}
{% get_static_prefix as STATIC_PREFIX %}
<head>
...
<script>    
jQuery(window).load(function() {
    $('#language').change(function() {
        window.location.replace("/" + $('#language').val() + "/index");
    });
});
</script>
...
</head>

<body>
....
<select id="language" name="language">
    {% if CURRENT_LANGUAGE == 'es' %}
        <option value="es" selected="yes">{% trans "Espaniol" %}</option>
    {% else %}
        <option value="es">{% trans "Espaniol" %}</option>
    {% endif %}
    {% if CURRENT_LANGUAGE == 'en' %}
        <option value="en" selected="yes">{% trans "Ingles" %}</option>
    {% else %}
        <option value="en">{% trans "Ingles" %}</option>
    {% endif %}
</select>
...
</body>

      

+1


source







All Articles