Django render_to_string 行为

And*_*unt 1 python django django-templates

我有以下 HTML 文件 template.html:

{% load i18n %}
<p>{% blocktrans %}You have following email: {{ request.user.email }}.{% endblocktrans %}</p>
Run Code Online (Sandbox Code Playgroud)

现在在Python中:

if request.user is not None and request.user.is_authenticated():
   text = render_to_string('template.html', context_instance=RequestContext(request)))
Run Code Online (Sandbox Code Playgroud)

但 request.user.email 在模板中为空。即使我写了{{ user.email }},它仍然是空的。如何正确呈现用户并调用其方法?例如,{{ request.user.get_short_name }}也不起作用。

更新:问题在于{% blocktrans %}

<p>You have following email: {{ request.user.email }}.</p>
Run Code Online (Sandbox Code Playgroud)

有人能告诉为什么吗?我还没有翻译消息,但我认为它会按原样呈现。

bru*_*ers 5

如文档所述,您不能直接在 a 中使用模板表达式{% blocktrans %},只能使用变量:

\n\n
\n

要翻译模板表达式 \xe2\x80\x93,例如访问对象属性\n 或使用模板过滤器 \xe2\x80\x93,您需要将表达式绑定到本地\n 变量以在翻译块中使用。例子:

\n
\n\n
{% blocktrans with amount=article.price %}\nThat will cost $ {{ amount }}.\n{% endblocktrans %}\n
Run Code Online (Sandbox Code Playgroud)\n\n

cf https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#blocktrans-template-tag

\n\n

所以你的模板代码应该是这样的:

\n\n
{% load i18n %}\n<p>\n{% blocktrans with email=request.user.email %}\n You have following email: {{ email }}.\n{% endblocktrans %}\n</p>\n
Run Code Online (Sandbox Code Playgroud)\n