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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…