Can we give dynamic queryset for ModelChoiceField in django forms?

ぃ、小莉子 提交于 2019-12-13 16:25:46

问题


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?


回答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:

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)


来源:https://stackoverflow.com/questions/22589190/can-we-give-dynamic-queryset-for-modelchoicefield-in-django-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!