Django translation.activate() - 在哪里做以及如何调试?

Django translation.activate() - where to do so and how to debug?

我有一个多语言网站。但是,访问者永远不应选择这些语言,而是 a) 根据域名决定(同一站点在不同的域下运行,每种语言一种),或 b) 根据确切的页面从数据库中检索打开。

manual 我了解到我应该使用 django.utils.translation.activate() 函数来明确设置语言。但是,我运气不好。

如果我没记错的话,这就是我需要的代码(不需要我设置cookie,所以这是我隔离的):

from django.utils import translation
translation.activate("fr")

这样对吗?我到底应该把它放在哪里?我可以使用站点框架将一种语言 link 转换为特定语言吗?这是我在 views.py 文件中尝试过的方法,但它不起作用。没有错误 - 只是没有翻译。有什么方法可以调试它以找出问题所在吗?

# views.py
from .models import *
from django.shortcuts import render
from django.utils import translation
from django.conf import settings

# I am trying to activate a default setting for the site, based on the domain of the site
if settings.SITE_ID == 1:
    translation.activate("fr")
else:
    translation.activate("en")

def homepage(request)
    return render(request, "index.html")

def listing(request, id)
    listing = Listing.objects.get(pk=id)
    language = listing.language
    translation.activate(language) # For particular pages, I need a different language, based on a value from the database. This is what I tried.
    return render(request, "index.html")

根据您的用例,使用 translation.activate() 的最佳位置是在某些中间件中,因为语言是 site/domain 相关的。

当你在做的时候:

# views.py
from .models import *
from django.shortcuts import render
from django.utils import translation
from django.conf import settings

# I am trying to activate a default setting for the site, based on the domain of the site
if settings.SITE_ID == 1:
    translation.activate("fr")
else:
    translation.activate("en")

在解析模块时进行调用,而不是在发出和处理 HTTP 请求时进行调用。

使用中间件,可以像这样选择合适的语言环境:

# middlewares.py
def site_locale_middleware(get_response):

    def middleware(request):
        if request.site.id == 1:
           translation.activate("fr")
        elif request.site.id == 2:
           translation.activate("es")
        else:
           translation.activate("en")

        response = get_response(request)

        return response

    return middleware 

并在您的设置中添加:


MIDDLEWARES = [
    "django.contrib.sites.middleware.CurrentSiteMiddleware""",
    # your middleware should be placed after CurrentSiteMiddleware
    # so that request.site is available
    "yourproject.middlewares.site_locale_middleware",
]

这将确保您为每个站点设置正确的语言,并且您可以在需要时使用以下方法覆盖它:

def listing(request, id)
    listing = Listing.objects.get(pk=id)
    language = listing.language
    with translation.override(language):
       # using override here is important, because it means it will only override 
       # the language when the response is rendered, and revert back to the previous language afterwards
       return render(request, "index.html")