如何在Django的urls.py中按用户选择的语言翻译**kwargs参数
解决Django中URL kwargs翻译跟随用户语言的问题
问题根源
你的代码里,pgettext在项目启动解析urlpatterns时就执行了,用的是settings.py里的LANGUAGE_CODE默认值,不会随每个请求的Accept-Language头变化。要让翻译跟随用户语言,必须把翻译逻辑移到请求处理阶段(也就是视图内部),这时候才能拿到当前请求对应的语言设置。
可行实现方案
方案一:视图内动态生成翻译内容(推荐)
直接把翻译逻辑放到视图的上下文生成方法里,移除URL中静态传递的kwargs:
修改urls.py:
from django.urls import path from main.views import SharedIndexView app_name = 'some_site' urlpatterns = [ path('', SharedIndexView.as_view()), ]
修改SharedIndexView视图:
from django.views.generic import TemplateView from django.utils.translation import pgettext class SharedIndexView(TemplateView): template_name = 'index.html' # 替换成你的模板路径 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # 这里的翻译会自动使用当前请求的用户语言 context['SITE_SEO_title'] = pgettext('home', 'SITE_SEO_title') return context
方案二:在视图dispatch方法中更新kwargs
如果必须通过kwargs传递参数,可以在视图的dispatch方法(每个请求都会触发)里动态替换翻译值:
from django.views.generic import TemplateView from django.utils.translation import pgettext class SharedIndexView(TemplateView): template_name = 'index.html' def dispatch(self, request, *args, **kwargs): # 动态翻译并更新kwargs kwargs['SITE_SEO_title'] = pgettext('home', 'SITE_SEO_title') return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # 直接使用已翻译好的kwargs值 context['SITE_SEO_title'] = kwargs['SITE_SEO_title'] return context
方案三:用可调用对象封装翻译逻辑(不推荐)
把kwargs的值设为一个可调用函数,在视图里调用它获取翻译结果:
修改urls.py:
from django.urls import path from main.views import SharedIndexView from django.utils.translation import pgettext def get_seo_title(): return pgettext('home', 'SITE_SEO_title') app_name = 'some_site' urlpatterns = [ path('', SharedIndexView.as_view(), {'SITE_SEO_title': get_seo_title}), ]
修改视图:
from django.views.generic import TemplateView class SharedIndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) seo_title_func = kwargs.get('SITE_SEO_title') if callable(seo_title_func): context['SITE_SEO_title'] = seo_title_func() return context
总结
最简洁可靠的是方案一,直接在视图上下文生成时处理翻译,完全贴合Django的请求处理流程,避免不必要的复杂逻辑。
内容的提问来源于stack exchange,提问作者Karolis
相关产品推荐
相关产品推荐

