gpt4 book ai didi

python - Django render_to_string 行为

转载 作者:太空宇宙 更新时间:2023-11-04 10:29:10 24 4
gpt4 key购买 nike

我有以下 HTML 文件 template.html:

{% load i18n %}
<p>{% blocktrans %}You have following email: {{ request.user.email }}.{% endblocktrans %}</p>

现在在 python 中:

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

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

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

<p>You have following email: {{ request.user.email }}.</p>

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

最佳答案

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

To translate a template expression – say, accessing object attributes or using template filters – you need to bind the expression to a local variable for use within the translation block. Examples:

{% blocktrans with amount=article.price %}
That will cost $ {{ amount }}.
{% endblocktrans %}

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

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

{% load i18n %}
<p>
{% blocktrans with email=request.user.email %}
You have following email: {{ email }}.
{% endblocktrans %}
</p>

关于python - Django render_to_string 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27888621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com