Login

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

Author:
jpic
Posted:
December 31, 2008
Language:
Python
Version:
1.0
Tags:
hack form queryset modelchoicefield modelform modelmultiplechoicefield
Score:
-1 (after 1 ratings)

Example view code:

lazy_field_options = {                             
    'field_name_that_is_m2m': {
        'queryset': YourRelatedModel.objects.filter(groups=request.user.groups.all()),
    },
    'field_name_that_is_fk': {
        'queryset': YourOtherRelatedModel.objects.filter(slug=request_slug),
    },
}
modelform = YourModelForm(jpic_field_options=lazy_field_options)
# after the modelform has called for parent __init__, it will set
# options for each field if possible.
 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. ModelChoiceField with choice groups for recursive relationships by estecb 1 year, 2 months ago
  2. A Lazy ModelChoiceField implementation by alecdotico 1 year, 8 months ago
  3. A ModelChoiceField with support for title in options based on a field in the model by celopes 4 years, 7 months ago
  4. ModelChoiceField with option groups by anentropic 3 years, 3 months ago
  5. CustomChoiceField, Selectable label field version of ModelChoiceField by mauro 7 years ago

Comments

Please login first before commenting.