django - 动态更改 Django ModelForm 中的字段选择

标签 django django-models django-forms

我在模型上有一个字段,如下所示:

class MyModel(models.Model):
    status_field = models.NullBooleanField(blank=False,
                                          verbose_name="Status",
                                          choices=((True, 'Approved'),
                                                   (False, 'Denied'),
                                                   (None, 'Pending')))

然后我有这个模型的 ModelForm 。在那个 ModelForm 中,我想有条件地/动态地删除这些选择之一。我目前正在尝试:
class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)


        if self.instance and self.instance.status_field is not None:
            self.fields['status_field'].choices.remove((None, 'Pending'))
            print self.fields['status_field'].choices

我可以从打印语句中看出该选项确实被删除了。但是,我一定遗漏了一些东西,因为在呈现表单时,该字段的小部件仍然包含我删除的选项。

实际上,我正在尝试做的是防止该字段在提供了值后变为 None/null。为了方便用户,我想在下拉列表中删除该选项。

谢谢您的帮助!

最佳答案

然后表单被初始化choices属性从字段复制到字段的小部件。所以你也必须从小部件中删除选择:

if self.instance and self.instance.status_field is not None:
    new_choices = list(self.fields['status_field'].choices)
    new_choices.remove((None, 'Pending'))
    self.fields['status_field'].choices = new_choices
    self.fields['status_field'].widget.choices = new_choices

关于django - 动态更改 Django ModelForm 中的字段选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28509742/

相关文章:

python - 获取 ModelForm 字段的值

python - Django 表单集 can_delete header

django - 在 Django 中保存嵌套表单

javascript - 将 Django 与大多数静态页面结合使用

django - 在 django 中启用 keep-alive 以实现持久连接

django - 清除某些应用程序或页面的 Django 缓存

python - 如何通过单独模型中最新对应条目中的文本字段过滤 Django 查询集

python - 具有字段名称值的 Django ManyToMany 字段

python - 你如何在 Django 中动态隐藏表单字段?

javascript - 如何从模型渲染多个选择字段