[Django]-Adding extra HTML tags and attributes to Django crispy-forms fields

2๐Ÿ‘

  1. For completeness, but not for your case: even after layout creation, Layout.wrap('recipients', Div) will work if one only needs to wrap a control into an additional Div.

  2. About adding HTML inside the layout. Last hour I needed a very custom HTML, so did this:

(formatting)

i = self.helper.layout.fields.index('guest_email')
self.helper.layout.insert(
    i+1,
    HTML('<a href="{}">{}</a>'.format(
        reverse_lazy('invite_guests'),
        _('Invite to a party'))
))

I came here googling for a HTMLWrapper class example for Crispy Forms, so that I could do a prettier thing instead:

self.helper['guest_email'].wrap(HTMLWrapper(
    'guest_email', 
     before='',
     after='<a href="{}">{}</a>'.format(href, title))

If I end up creating one, Iโ€™ll get back and post it.

0๐Ÿ‘

For me it worked that way:

from crispy_forms.layout import Field, HTML

self.helper["some_field_name"].wrap(Field, HTML("<p>Example</p>"))

The benefit of using HTML is that it also gives you the possibility to use context variables.

๐Ÿ‘คmbijou

Leave a comment