Skip to content Skip to sidebar Skip to footer

Can We Give Dynamic Queryset For Modelchoicefield In Django Forms?

I want create a model form, which has a foreign key in the model. Like: class TestModel(Model): field1=ForeignKey(RefModel) I create a form like: class TestForm(ModelForm):

Solution 1:

You can override the field. use

field1 = ModelChoiceField(queryset=<<your_queryset_here>>, widget=RadioSelect)

you can also override this queryset in the __init__ method and adjusting the field accordingly:

classTestForm(ModelForm):
    field1 = ModelChoiceField(queryset=<<your_queryset_here>>, widget=RadioSelect)

    classMeta(object):
        model = TestModel

    def__init__(self, **kwargs):
        super(TestForm, self).__init__(**kwargs)
        self.fields['field1'].queryset = kwargs.pop('field1_qs')

and initiating the form accordingly in the view that manages it.

my_form = TestForm(field1_qs=MyQS)

Post a Comment for "Can We Give Dynamic Queryset For Modelchoicefield In Django Forms?"