TAGS :Viewed: 10 - Published at: a few seconds ago

[ Passing a kwargs parameter to a ModelForm Field constructor? ]

How can I pass a parameter in to a ModelForm Field constructor?

class ThingSettingsForm(ModelForm):
    things = forms.ModelChoiceField(empty_label='--',queryset=self.?????)

    def __init__(self, *args, **kwargs):
        super(ThingSettingsForm, self).__init__(*args, **kwargs)
        if 'instance' in kwargs:
            instance = kwargs['instance']
            ?????? = instance.visible_things
            #self.fields['things'] = 

    class Meta:
        model = Gallery
        fields = (

In the underlying model 'things' is a models.ForeignKey, and the default of showing every possible relation is not appropriate.

Answer 1

If visible_things is a queryset, you can change the queryset attribute of the form field:

self.fields['things'].queryset = instance.visible_things

It really does have to be a queryset, not an arbitrary iterable, but other than that it's easy.

Answer 2

Just add a kwarg if the arg is optional:

myform = ThingSettingsForm(thing=<my instance>)

You'll have to change the init method to pop your new arg first, as super isn't expecting this arg:

def __init__(self, *args, **kwargs):
    instance = kwargs.pop('thing', None)
    super(ThingSettingsForm, self).__init__(*args, **kwargs)

Or if its required, just add it into the init signature:

def __init__(self, thing, *args, **kwargs):

and call it thus:

myform = ThingSettingsForm(<my instance>)