Login

Dynamically alter the attributes of a formset

Author:
cronosa
Posted:
May 31, 2010
Language:
Python
Version:
1.2
Tags:
dynamic formset attributes
Score:
2 (after 2 ratings)

Allow you to specify a "General case formset/modelformset" and then alter the attributes of that formset, specificly: extra, can_order, can_delete and max_num.

So you specify:

formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O')) and then you want to dynamically add multiple fields with javascript and save the new ones. By default a formset only has 1 extra field. With this you can return a new formset (using the same queryset, forms, formset base class, etc) but with different attributes. So you could then add 10 extra fields if the user added 10 new forms.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django.forms.formsets import formset_factory

def dynamic_formset(formset, extra=None, can_order=None, can_delete=None, max_num=None):
    if extra is None:
        extra = formset.extra
    if can_order is None:
        can_order = formset.can_order
    if can_delete is None:
        can_delete = formset.can_delete
    if max_num is None:
        max_num = formset.max_num
    return formset_factory(form = formset.form, 
                         formset = formset.__class__, 
                         extra = extra, 
                         can_order = can_order, 
                         can_delete = can_delete, 
                         max_num = max_num)
    

More like this

  1. Complex Formsets, Redux by smagala 5 years, 4 months ago
  2. Arbitrary length formset by Rupe 5 years, 11 months ago
  3. Complex Formsets by smagala 6 years, 6 months ago
  4. Different number of extra formsets in add/change view of ModelAdmin. by xormag 4 years ago
  5. Dynamic Django form by rufman 7 years, 3 months ago

Comments

Please login first before commenting.