Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django and fieldsets on ModelForm

I know you can specify fieldsets in django for Admin helpers. However, I cannot find anything useful for ModelForms. Just some patches which I cannot use. Am I missing something? Is there a way I could achieve something like fieldsets without manually writing out each field on my template in the appropriate tag.

I would ideally like to iterate through a set of BoundFields. However, doing something like this at the end of my ModelForm:

    fieldsets = []     fieldsets.append(('Personal Information',                       [username,password,password2,first_name,last_name,email]),) # add a 2 element tuple of string and list of fields     fieldsets.append(('Terms & Conditions',                       [acceptterms,acceptprivacy]),) # add a 2 element tuple of string and list of fields 

fails as the items contained in my data structure are the raw fields, not the BoundFields. t looks like BoundFields are generated on the fly... this makes me sad. Could I create my own subclass of forms.Form which contains a concept of fieldsets (even a rough one that is not backward compatible... this is just for my own project) and if so, can you give any pointer? I do not want to mess with the django code.

like image 527
Krystian Cybulski Avatar asked Feb 06 '09 03:02

Krystian Cybulski


People also ask

What is Fieldsets in Django admin?

I think you have misunderstood what fieldsets are. It's just a way for you to be able to group the fields on a Model Admin Page.

How do you make a field not required in Django?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).

How do you make a field optional in Django?

If you want to allow blank values in a date field (e.g., DateField , TimeField , DateTimeField ) or numeric field (e.g., IntegerField , DecimalField , FloatField ), you'll need to use both null=True and blank=True . Show activity on this post. Use null=True and blank=True in your model.

What is Fieldset Django?

HTML forms contain a construct called a fieldset . These are generally used to segment a form: splitting a form into groups of fields that are logically grouped. Each fieldset may also have a legend.


1 Answers

I think this snippet does exactly what you want. It gives you a Form subclass that allows you to declaratively subdivide your form into fieldsets and iterate through them in your template.

Update: that snippet has since become part of django-form-utils

like image 87
Carl Meyer Avatar answered Sep 18 '22 22:09

Carl Meyer