Lazy options on ModelForm fields - like setting a ModelChoiceField queryset from the view

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# todo : get a more descriptive FC prefix than "jpic"
class JpicModelForm(forms.ModelForm):
    """
    Inherit from this, then use this new keyword argument
    'jpic_field_options' with a dict of dicts such as:
    {                             
        'field_name_that_is_m2m': {
            'queryset': aqueryset,
        },
        'field_name_that_is_fk': {
            'queryset': anotherqueryset,
        },
    }

    This solves the problem of using a queryset made in the view
    as choices for a M2M/FK field ...
    """
    def __init__(self, *args, **kwargs):
        if 'jpic_field_options' in kwargs.keys():
            jpic_field_options = kwargs.pop('jpic_field_options')
        super(JpicModelForm, self).__init__(*args, **kwargs)
        for field, args in jpic_field_options.items():
            if field not in self.fields:
                continue 
            for arg, value in args.items():
                setattr(self.fields[field], arg, value)

More like this

  1. Edit users on Group admin by cedriccollins 1 year, 11 months ago
  2. filtered ModelChoiceField queries by robharvey 5 years, 2 months ago
  3. FieldLevelPermissionsAdmin by buriy 5 years, 8 months ago
  4. ModelChoiceField with optiongroups by anentropic 3 years, 2 months ago
  5. Limit ForeignKey filter values to those that have a relationship with current model by overclocked 2 years, 6 months ago

Comments

jpic (on January 13, 2009):

I was asked how this could be useful when you could do like: http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/

It's useful to me because then all forms init() method can keep the same signature, making it usable in a factory.

#

(Forgotten your password?)