国际化基于 Django class 的通用视图 (CreateView)?

Internationalizing a Django class-based generic view (CreateView)?

我正在使用 Django 1.9 class-based generic views, for example CreateView。当我访问 "create" 页面时,一些部分被翻译(在我的例子中翻译成法语),所以我知道我的配置和接线是正确的,但表单字段(由视图自动命名)不是(即 form.as_p).

如何从我的翻译文件中获取要使用的表单域? (例如,"Name" 是一个字段,已经翻译,但未被 form.as_p 拾取)。

一个答案是在模板中用 {% trans %} 标签单独列出字段。我希望避免这种情况。

我的示例与 the docs 中的示例类似,所以让我在这里重复该示例。一、代码:

from django.views.generic.edit import CreateView
from myapp.models import Author

class AuthorCreate(CreateView):
    model = Author
    fields = ['name']

然后显示模板:

<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save" />
</form>

看看 Lazy Translation:

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.

所以,如果你有表格,你可以使用ugettext_lazy来翻译:

from django.db import models
from django.utils.translation import ugettext_lazy as _

class MyThing(models.Model):
    name = models.CharField(help_text=_('This is the help text'))

You can mark names of ForeignKey, ManyToManyField or OneToOneField relationship as translatable by using their verbose_name options:

class MyThing(models.Model):
    kind = models.ForeignKey(
        ThingKind,
        on_delete=models.CASCADE,
        related_name='kinds',
        verbose_name=_('kind'),
    )