Why do I get NameError: name '_' is not defined when setting custom templates for djangocms-video?

Why do I get NameError: name '_' is not defined when setting custom templates for djangocms-video?

我正在尝试让自定义模板适用于 djangocms-video。

到目前为止,有一个新的 djangocms 项目设置了一些 bootstrap 和 运行 很好。

根据 readme,我们需要在 settings.py 中指定此内容才能使自定义模板可用(在本例中为名为“feature”的模板):

DJANGOCMS_VIDEO_TEMPLATES = [
    ('feature', _('Featured Version')),
]

设置此后 运行 manage.py 出现此错误:

    ('feature', _('Featured Version')),
NameError: name '_' is not defined

According to other threads 我们需要在 modely.py 中像这样导入 gettext: from django.utils.translation import gettext as _ 或者像这样: django.utils.translation import ugettext_lazy as _

到目前为止运气不好。我在这里错过了什么?

这里有一些关于环境的信息:

python --version
Python 3.9.2
pip list
Package                    Version
-------------------------- -----------
asgiref                    3.4.1
cssselect2                 0.4.1
dj-database-url            0.5.0
Django                     3.1.14
django-classy-tags         2.0.0
django-cms                 3.8.0
django-filer               2.1.2
django-formtools           2.3
django-js-asset            1.2.2
django-mptt                0.13.4
django-polymorphic         3.0.0
django-sekizai             2.0.0
django-treebeard           4.5.1
djangocms-admin-style      2.0.2
djangocms-attributes-field 2.0.0
djangocms-bootstrap4       2.0.0
djangocms-file             3.0.0
djangocms-googlemap        2.0.0
djangocms-icon             2.0.0
djangocms-installer        2.0.0
djangocms-link             3.0.0
djangocms-picture          3.0.0
djangocms-style            3.0.0
djangocms-text-ckeditor    4.0.0
djangocms-video            3.0.0
easy-thumbnails            2.8
html5lib                   1.1
lxml                       4.7.1
Pillow                     9.0.0
pip                        21.3.1
pkg_resources              0.0.0
pytz                       2021.3
pytz-deprecation-shim      0.1.0.post0
reportlab                  3.6.5
setuptools                 44.1.1
six                        1.16.0
sqlparse                   0.4.2
svglib                     1.1.0
tinycss2                   1.1.1
tzdata                     2021.5
tzlocal                    4.1
Unidecode                  1.1.2
webencodings               0.5.1

在 Django 中,gettext_lazy(…) function [Django-doc] is often imported as _ to manage translations. This is explained in the Standard translation:

Python’s standard library gettext module installs _() into the global namespace, as an alias for gettext(). In Django, we have chosen not to follow this practice, for a couple of reasons

(…)

Because of how xgettext (used by makemessages) works, only functions that take a single string argument can be imported as _:

因此您应该添加:

from django.utils.translation <strong>import gettext_lazy as _</strong>

在文件的顶部。

如果您这样定义类似 _('Featured Version') 的内容,您可以 运行 makemessages 生成翻译文件并填写每种语言的翻译。