3

我有一个具有preferred_language字段的自定义用户模型。我希望将所有电子邮件(激活和密码重置)翻译成用户在配置文件中指定的语言。

class CustomUser(AbstractBaseUser, PermissionsMixin):
    ...
    LANGUAGE_CHOICES = (
        (1, "English"),
        (2, "Русский")
    )

    preferred_language = models.PositiveSmallIntegerField(choices=LANGUAGE_CHOICES, default=2,
                                                          verbose_name=_("Preferred language"))

我考虑过设置自定义电子邮件类,但在 navive djoser 的课程中​​没有看到任何我可以明确设置结果电子邮件语言的点,尽管电子邮件模板有待翻译的样式:

class ActivationEmail(BaseEmailMessage):
    template_name = 'email/activation.html'

    def get_context_data(self):
        context = super(ActivationEmail, self).get_context_data()

        user = context.get('user')
        context['uid'] = utils.encode_uid(user.pk)
        context['token'] = default_token_generator.make_token(user)
        context['url'] = settings.ACTIVATION_URL.format(**context)
        return context

重置密码视图(settings.EMAIL.activation在上面的 ActivationEmail 类中使用了它的参考):

class ResetPassword(ActionViewMixin, generics.GenericAPIView):
    ...

    def send_password_reset_email(self, user):
        context = {'user': user}
        to = [get_user_email(user)]
        settings.EMAIL.password_reset(self.request, context).send(to)

    def send_activation_email(self, user):
        context = {'user': user}
        to = [get_user_email(user)]
        settings.EMAIL.activation(self.request, context).send(to)
4

1 回答 1

2

在您的情况下,我将使用override在输入时存储当前语言的上下文管理器(以便发送电子邮件)并在退出时恢复它。

from django.utils import translation


def send_password_reset_email(self, user):
    context = {'user': user}
    to = [get_user_email(user)]
    lang_code = user.lang_code  # retrieve user's language code here
    with translation.override(lang_code):
        settings.EMAIL.password_reset(self.request, context).send(to)

def send_activation_email(self, user):
    context = {'user': user}
    to = [get_user_email(user)]
    lang_code = user.lang_code  # retrieve user's language code here
    with translation.override(lang_code):
        settings.EMAIL.activation(self.request, context).send(to)
于 2019-10-06T18:47:45.050 回答