Django: how to include url link in form label

My use case looks very simple, but I did not find anything on the Internet!

An idea is a form with a flag β€œI have read and agree to the terms” and a link to β€œterms” that 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 message:

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

My urlconf works fine on the whole site, so I assumed that the problem is that urlconf is not populated yet when the form is displayed?

I tried using lazy_reverse = lazy (reverse, str) instead of the opposite, but does not solve anything.

Is there any way to make this work? The use case seems very simple, so of course there is a way to do this without breaking the form inside my template ?!

+4
source share
2 answers

lazy_reverse will not work because you are turning and will not recognize it second after your notation "...%s..." % lazy(blah) .

I suppose you could try to lazy everything, i.e.

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

but I have not tested this

just override the label in __init__ , i.e.

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

You can provide a link to the form label as follows:

 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
source

All Articles