Skip to main content
 首页 » 编程设计

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

2025年05月04日44pander-it

我想将解析后的 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 .因此,请使用它而不是重新创建它。