开发者

Django: how do I include a url link in a form label

My use case looks very basic but I couldn't find anything on the web!

The idea is a form with checkbox "I have read and agree to the terms and conditions" And a link on "terms and conditions" which points to a page with such terms and conditions... Classic!

So I have a field in my form as follows:

tos = forms.BooleanField(widget=forms.CheckboxInput(),
                         label=_(u'I have read and agree to the <a href="%s" target="_blank">terms and conditions</a>' % reverse('terms_of_use')),
                         initial=False)

where 'terms of use' is the name of one of my url patterns in urls.py

But I get an error:

ImproperlyConfigured: The included urlconf urls doesn't have any patterns in it

My urlconf works fine on the whole site so I supposed that the problem was that the urlconf is not yet populated when the form is rendered ?

I tried using lazy_reve开发者_StackOverflowrse = lazy(reverse, str) instead of reverse, but it doesn't solve anything.

Is there a way to make this work ? The use case seems very very basic so there surely is a way to do it without having to break up the form inside my template ?!


lazy_reverse won't work since you're turning around and unlazying it the second after with your "...%s..." % lazy(blah) notation.

I suppose you could try to lazy the whole thing, i.e.

label = lazy(lambda: _("bla %s bla" % reverse('something')))

but I did not test this

alternatively, just override the label at __init__, i.e.

self.fields['myfield'].label = 'blah %s bla' % reverse('bla')


I use this syntax

from django.urls import reverse
from django.utils.functional import lazy

privacy = forms.BooleanField(label = lazy(lambda: _("Privacy <a href='%s' a>policy</a>" % reverse('privacy'))))


You can provide a link a form label like this:

foo_filter=forms.ModelChoiceField(FooFilter.objects.all(),
               label=format_html('<a href="{}">{}</a>', reverse_lazy('foo-filter'), 
                                 FooFilter._meta.verbose_name))

See AppRegistryNotReady: lazy format_html()?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜