Reputation: 5850
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):
class Meta(object):
model = TestModel
widgets = {'field1': RadioSelect}
But I want to do some limitation on the field according to the url, which means it's not constant data, what should I do to change the queryset for field1 of TestForm?
Upvotes: 2
Views: 3751
Reputation: 2790
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:
class TestForm(ModelForm):
field1 = ModelChoiceField(queryset=<<your_queryset_here>>, widget=RadioSelect)
class Meta(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)
Upvotes: 4