python - 以 Django 形式翻译占位符

标签 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    )

这是我的模板 .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>

这是我的 .po 文件:

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

最佳答案

尝试使用ugettext_lazy:

from django.utils.translation import ugettext_lazy as _

代替

from django.utils.translation import ugettext as _

来自文档(参见粗体):

These functions store a lazy reference to the string – not the actual translation. The translation itself will be done when the string is used in a string context, such as in template rendering.

This is essential when calls to these functions are located in code paths that are executed at module load time.

This is something that can easily happen when defining models, forms and model forms, because Django implements these such that their fields are actually class-level attributes. For that reason, make sure to use lazy translations in the following cases:

关于python - 以 Django 形式翻译占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29225750/

相关文章:

python - 如何从具有更改日志的表和 Django 中的事件表中获取可以推迟给定日期的事件?

python - django 模型中的硬编码属性

python - 在 gnuplot 中绘制 pm3d map 的 python 类比是什么?

Python:无法匹配后跟分词符的句点(在非捕获组中)

python - 如何在 Django 中的多对多关系中向数据透视表添加更多列?

python - 如何在 Django 中使用 toastr 获取成功或失败消息

python - 旋转 Pandas 表 - 特殊问题

python - Sklearn 数字数据集

python - Pytorch 相当于 Numpy 的 logical_and 和 kin?

python - Django AWS Elastic Beanstalk 错误 ImproperlyConfigured : Error loading MySQLdb module: No module named MySQLdb