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?
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.