如何在Django HTML中导入模块?

Hat*_*out 1 python django django-templates django-models

我有一个django博客。我需要使用附魔来检查博客文章中的文本是否为英文,然后在文本错误更正中使用api。

我将api安装在django博客的虚拟环境中

pip安装pyenchant

项目,并将其包含在已安装的应用程序中,但是在博客base.html中,我尝试加载它并使用它的功能来检查帖子标题是否为英文,但是我什么也没做。如何解决呢?这是我的html代码:

{% load enchant %}

{% dictionary = enchant.Dict("en_US") %}
<p>{% dictionary.check(post.title) %}</p>
Run Code Online (Sandbox Code Playgroud)

当我运行服务器时没有错误,但是html页面上没有任何内容。注意:根据API,在段落标记中应该为True of False。“我在python shell中对其进行了测试。”

1ro*_*mat 5

你不能这样做。跟着我 :)

没有与pyenchant现有的模板标签与Django的工作(我从DOC学习)。您的代码dictionary = enchant.Dict("en_US")在django后端上还可以,但是也不适合django模板。

因此,要做到这一点,您可以创建一个自定义模板标签,以在python代码和模板语言之间建立连接。

您可以执行以下操作,它可以:

templatetags
templatetags/__init__.py
templatetags/pyenchant_tags.py
Run Code Online (Sandbox Code Playgroud)

templatetags / pyenchant_tags.py文件

import enchant
from django import template

register = template.Library()

@register.simple_tag
def please_enchant_my_string(language, string):
    d = enchant.Dict(language)
    return d.check(string)
Run Code Online (Sandbox Code Playgroud)

模板的一部分,与我们的标签调用:

{% load pyenchant_tags %}

<div>
    {% please_enchant_my_string 'en_US' post.title %}
</div>
Run Code Online (Sandbox Code Playgroud)