Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

Django translation.activate doesn't work when redirect

I have a two-language Django website and when I want to change the language, it doesn't work.

Here is the links in the template to change the language:

<a href="{% url 'change_lang' %}?lang=en&next={{ request.path }}">EN</a>
<a href="{% url 'change_lang' %}?lang=fa&next={{ request.path }}">FA</a>

As you can see, I send the language that I want and the current path as parameters for the view.

This is the urls.py:

from .views import change_language

urlpatterns = [
    path('change_lang', change_language, name='change_lang'),
]

And this is the views.py:

from django.utils.translation import activate

def home(request):
    # My commands

    # activate('fa')

    context = {
        # Some key and values
    }
    return render(request, 'home.html', context)


def change_language(request):
    activate(request.GET.get('lang'))
    return redirect(request.GET.get('next'))

And I've added these two line in the settings.py as well:

LANGUAGES = [
    ('fa', 'Persian'),
    ('en', 'English'),
]

And I found that activate(request.GET.get('lang')) doesn't work.

But when I uncomment the activate('fa') in the home view, It does work. But this command doesn't work in the change_language method.

I've found that it is because of the redirect method. I replace the redirect with render and then the activate works!

How can I do activate a language and then redirect?

Thanks for your help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...