Django. i18N 反向URL问题

1 投票
1 回答
940 浏览
提问于 2025-04-18 03:54

这个问题只在生产服务器上出现。在设置中的语言看起来是这样的:

`LANGUAGE_CODE = 'pl'
LANGUAGES = [
    ('pl', gettext('PL')),
    ('en', gettext('EN')),
]`

@register.simple_tag(takes_context=True)
def unsubscribe_link(context, href):
    domain = 'http://' + Site.objects.get_current().domain
    a = '<a href="%s" target="_self">%s</a>'
    if context.get('preview'):
        return a % ('#', href)
    return a % (domain + context['participant'].get_unsubscribe_url(), href)

models.participant :

    @models.permalink
    def get_unsubscribe_url(self):
        return ('participant-unsubscribe', [self.pk, self.unsubscribe_hash])

问题是,unsubscribe_link这个模板标签返回的链接格式是:域名/en-us/xxx/xxx,显然这个链接返回的是404错误。要是我把“en-us”改成“pl”,一切就正常了。我找不到这个问题的根源。在本地,链接生成得很好。

1 个回答

1

我觉得你的问题和定时任务的地区设置有关:

  1. 你可以做的是创建一个文件(如果还没有的话)在 /etc/environment 这个路径下,然后添加以下这一行:

    LANG=pl_PL.UTF-8
    
  2. 修改你的命令:

class Command(BaseCommand):

    can_import_settings = True

    def handle(self, *args, **options):

        # Activate a fixed locale, e.g. Polish
        translation.activate('pl')

        # Or you can activate the LANGUAGE_CODE # chosen in the settings:
        #
        #from django.conf import settings
        #translation.activate(settings.LANGUAGE_CODE)

        # Your command logic here
        # ...

        translation.deactivate()

撰写回答