是否可以更改 django 管理员错误消息。
我想添加我的自定义错误消息。
请更正以下错误。更改此消息
class mymodel(admin.ModelAdmin):
# change message
是否可以更改 django 管理员错误消息。
我想添加我的自定义错误消息。
请更正以下错误。更改此消息
class mymodel(admin.ModelAdmin):
# change message
仔细阅读文档,我们可以看到我们可以覆盖基础翻译,如下:
在您的settings.py
中,添加/更新以下变量:
LOCALE_PATHS = [
os.path.join(BASE_DIR,"locale"),
]
manage.py
),创建一个名为locale
(或其他任何名称的文件夹,但如果您以不同的方式重命名它,也请在步骤 1 中进行更改)。locale
文件夹中,为要覆盖的每种语言创建一个文件夹。在我们的例子中,我们想要覆盖英语,所以我们需要创建一个名为en
en
文件夹中,创建另一个文件夹,命名为LC_MESSAGES
LC_MESSAGES
夹中,创建一个名为django.po
此时,locale 的内容应该是这样的
├── locale
│ └── en
│ └── LC_MESSAGES
│ └── django.po
现在我们需要在这个django.po
文件中添加我们想要从 Django 基本翻译中覆盖的任何字符串。您可以在源代码中找到它们。例如,在您的特定情况下,此文件告诉我们需要覆盖的字符串 id 在第 459 行:
msgid "Please correct the errors below."
我们使用该 id 来提供不同的字符串,因此将以下内容添加到django.po
文件中:
msgid "Please correct the errors below."
msgstr "Fix the errors now!"
在这种情况下,我将原始消息替换为"Fix the errors now!"
重新编译消息
django-admin compilemessages
此命令应输出应输出如下消息:
processing file django.po in /path/to/project/locale/en/LC_MESSAGES
Django 现在会以更高的优先级考虑这个文件并显示新消息:
One of the ways to solve this is by using translations, but that would require knowledge in editing .PO
files and you will have to make a lot of changes to your code.
Fortunately, Django allows you to include extra .css
files and .js
files to a ModelAdmin
.
The tricky idea is that you will create a javascript file in your static
directory, and inside that file you will replace whatever text you wish
/static
admin.js
// When the page is fully loaded
document.addEventListener('DOMContentLoaded', function()
{
// Replace whatever text you wish, line by line
document.body.innerHTML = document.body.innerHTML.replace(new RegExp('\\bPlease correct the errors below\\b', 'g'), 'Some fields are empty');
document.body.innerHTML = document.body.innerHTML.replace(new RegExp('\\bThis field is required\\b', 'g'), 'This field cannot be empty');
});
class mymodem(admin.ModelAdmin):
class Media:
js = ['admin.js']
....
OUTPUT :