2

I did makemessages, translated my strings that are {% translate 'my_string' %} in templates, and then compilemessages.

But set_language does not seem to be working.

My only translated language is es, en in the other hand is the native language of my project.

navbar.html:

<form action="{% url 'set_language' %}" method="POST" enctype="application/x-www-form-urlencoded">
    {% csrf_token %}
    <input id="id_language" name="language" value="es" type="hidden">
    <button type="submit" class="btn btn-outline-info mx-1"><i class="fas fa-language"></i></button>
</form>

urls.py:

urlpatterns = [
    path('i18n/', include('django.conf.urls.i18n')),
    # ...
]

That's what I have. Then I put a pdb.set_trace() in one of my middlewares in order to check if the request is working as expected, and it does, when on debugger I type request.POST it has both the csrf_token and a language field with 'es' value.

After response, the language is still set to en instead of es. What could be happening? Am I missing something? Thanks!

1 Answer 1

1

It looks like you have to include the "next" value yourself. I whipped up a filter for use in templates:

'''
Tag to strip the language from a "request.get_full_path" in a template
so we can use the set_language view in templates.
'''
from django import template
from django.conf import settings

register = template.Library()


@register.filter
def strip_language(value):
    '''
    We are just taking off the first (leftmost) item in the path if it is in]
    the language lists
    '''
    parts = value.strip("/").split("/")
    language = parts.pop(0)
    if language in [lang[0] for lang in settings.LANGUAGES]:
        return "/{}".format("/".join(parts))
    return value

REFERENCE: https://code.djangoproject.com/ticket/28070

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.