Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting A Heading Into A Django Form

I would like my form to output something like this:

Name: ___________
Company: ___________

Interested in
-------------
Foo: [ ]
Bar: [ ]
Baz: [ ]

That is to say, I would like to have the 'Interested In' title inserted in the middle of my form output.

One way of doing this would be to write out the template code for each field, and insert the heading as appropriate. However, I'd prefer not to do this. I suspect that there is something to do with formsets that will do what I want.

Is there a way to do what I want, or do I just need to suck it up and accept that I need to write my template out longhand for this?

like image 893
Daniel Watkins Avatar asked Oct 14 '25 16:10

Daniel Watkins


1 Answers

Django formsets are not the way to go: They are used if you need to edit multiple objects at the same time. HTML fieldsets are more like the correct way. I imagine you could group the name and company fields into one fieldset, and then the interest fields into another.

On DjangoSnippets you can find a template tag that aids the grouping.

Using this snippet, you would define the grouping in your view as

fieldsets = (
    ('', {'fields': ('name','company')}),
    ('Interested in', {'fields': ('foo','bar','baz')})
)

Pass it to the template along with the form, and render the form with

{% draw_form form fieldsets %}

I would prefer not to define the grouping in the view, as it's mainly presentational issue and should belong to the view, but what the heck, this seems to do the job!

muhuk's solution though looks more elegant than this...

like image 169
Guðmundur H Avatar answered Oct 17 '25 11:10

Guðmundur H