python - 使用 Django 的 `reverse_lazy` 并将其连接起来

标签 python django

我想将解析后的 URL 插入到字符串中,用作表单字段的 help_text:

class ContactForm(forms.Form):

    [...]

    email_sender = forms.EmailField(
        label="Votre email",
        widget=forms.EmailInput(attrs={'disabled': 'disabled'}),
        help_text="[...], <a href='{}'>[...]</a>.".format(reverse_lazy('account_email'))
    )

但是将反向 URL 插入到字符串中是不可能的,因为 format 函数(或我尝试过的任何连接方式)不是“懒惰的”,而是想立即产生输出。

我收到以下错误:

django.core.exceptions.ImproperlyConfigured: The included urlconf 'myproject.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

例如,使用下面的代码效果很好,但不是我想要的:)

    email_sender = forms.EmailField(
        help_text=reverse_lazy('account_email')
    )

那么如何连接一串“惰性”值呢?

最佳答案

注意:这是在 Django 2 时代编写的。虽然本质在 Django 4 中仍然有效,但这篇文章中描述的辅助函数现在已开箱即用作为format_lazy .


您不能在 Django 中连接惰性字符串。实现非常基础,它甚至不是真正的惰性字符串,它是惰性函数调用,它们可能会返回其他类型。当您执行 reverse_lazy 时,您只会得到一个没有其他特殊行为的惰性函数调用

所以,只要遵守规则就行了。如果您需要延迟计算一个字符串,请自己创建一个延迟函数:

from django.utils.functional import lazy

def email_sender_help_text():
    return "[...], <a href='{}'>[...]</a>.".format(reverse('account_email'))

email_sender_help_text_lazy = lazy(email_sender_help_text, str)

您现在可以使用它了:

email_sender = forms.EmailField(
    help_text=email_sender_help_text_lazy()
)

或者,对于更通用的版本:

from django.utils.functional import lazy

def format(string, *args, **kwargs):
    return string.format(*args, **kwargs)
lazy_format = lazy(format, str)

help_text=lazy_format("<a href='{}'>", reverse_lazy('account_email'))

您可能还想查看 django.utils.functional.allow_lazy .


稍后编辑:
从 Django 3 开始,Django 提供了这个辅助函数,如 format_lazy .因此,请使用它而不是重新创建它。

关于python - 使用 Django 的 `reverse_lazy` 并将其连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31236234/

相关文章:

python - Django 如何在请求中传递基本授权 header ?

python - pyvisa 给出错误,但 linux-gpib 工作

python - 如何将 kivy 中的下拉列表与主按钮中心对齐?

python - 有没有办法自动检测 Django 模板中的链接?

python - 在 docker 中使用 selenium 运行 django 测试

python - Materialise css 'select' 不适用于 django

python - 如何在 Dropbox 更新特定目录后触发脚本执行?

python - XML 写入按元素分组的关系表

django - django-haystack现场 boost -究竟如何使用?

django - 无法在 Django 中获得 hello world