views:

274

answers:

3

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?

+3  A: 

With FieldsetMixin you get Admin-like fieldsets. You create your form like this:

from django.forms import Form
from formfieldset.forms import FieldsetMixin


class MyForm(Form, FieldsetMixin):
    fieldsets = (
        (u'', {'fields': ['name', 'company']}),
        (u'Interested in', {'fields': ['foo', 'bar', 'baz']}),
    )

    # rest of the form
muhuk
A: 

The form fields retain the order with which you defined the form class or model if it's form for model. In the template you can iterate thru all the fields specifying how they are rendered, you can check for the one you are looking for with the ifequal tag and specify the different rendering.

See:

http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#looping-over-the-form-s-fields

Vasil
+3  A: 

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...

Guðmundur H
Bookmarked the link. I'll check later. Thanks for sharing.
muhuk
I think it belongs in the form because the foo, bar and baz fields are conceptually related, I don't just want to insert a heading to make it look better.Anyhow, I'll look at these solutions once I've had my morning coffee. :)
Daniel Watkins