gpt4 book ai didi

python - 我们可以在 Django 表单中为 ModelChoiceField 提供动态查询集吗?

转载 作者:行者123 更新时间:2023-11-28 22:50:28 25 4
gpt4 key购买 nike

我想创建一个模型表单,它在模型中有一个外键。喜欢:

class TestModel(Model):
field1=ForeignKey(RefModel)

我创建了一个表单:

class TestForm(ModelForm):
class Meta(object):
model = TestModel
widgets = {'field1': RadioSelect}

但是我想根据url对字段做一些限制,也就是说它不是常量数据,我应该如何更改TestForm的field1的queryset?

最佳答案

您可以覆盖该字段。使用

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

您还可以在 __init__ 方法中覆盖此查询集并相应地调整字段:

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')

并在管理它的 View 中相应地启动表单。

my_form = TestForm(field1_qs=MyQS)

关于python - 我们可以在 Django 表单中为 ModelChoiceField 提供动态查询集吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22589190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com