Login

Dynamically alter the attributes of a formset

Author:
cronosa
Posted:
May 31, 2010
Language:
Python
Version:
1.2
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.