以Django形式翻译占位符

Mar*_*ind 3 python django

我在翻译文本输入字段的占位符文本时遇到问题.我已经将我的.po文件翻译为占位符的翻译,当我加载我的页面时,所有翻译工作正常,除了这个单独的占位符.是的,我编译了我的翻译文件.

似乎它不明白它应该显示翻译版本.也许创建表单时没有知道当前语言是什么的上下文.

如何解决这个问题?如何在Django中的窗体小部件中翻译占位符?

这是我的forms.py文件:

from django import forms
from django.utils.translation import ugettext as _

class InlineSearch(forms.Form):
    query = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control input-lg', 'placeholder':_('Search for a country, city or address here...')}), localize=True    )
Run Code Online (Sandbox Code Playgroud)

这是我的模板.html文件:

{% load i18n %}
<div class="inline-search">
    <div class="container">
        <form method="get" action="">
            <div class="input-group">
                {% for field in formset %}
                    {{field}}
                {% endfor %}
                <span class="input-group-btn">
                    <button type="submit" action="submit" class="btn btn-primary btn-lg"><i class="fa fa-search"></i> {% trans "Search" %}</button>
                </span>
            </div>
        </form>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是我的.po文件:

#: .\search\forms.py:5
msgid "Search for a country, city or address here..."
msgstr "Sök ett land, stad eller adress här..."
Run Code Online (Sandbox Code Playgroud)

mas*_*azi 8

尝试使用ugettext_lazy:

from django.utils.translation import ugettext_lazy as _
Run Code Online (Sandbox Code Playgroud)

代替

from django.utils.translation import ugettext as _
Run Code Online (Sandbox Code Playgroud)

从文档中看(见粗体):

这些函数存储对字符串的惰性引用 - 而不是实际的转换.当字符串在字符串上下文中使用时,例如在模板渲染中,将完成转换本身.

当对这些函数的调用位于在模块加载时执行的代码路径中时,这是必不可少的.

这在定义模型,表单和模型表单时很容易发生,因为Django实现了这些,使得它们的字段实际上是类级属性.因此,请确保在以下情况下使用延迟翻译: