django cms 插件上的动态模型选择字段

Posted

技术标签:

【中文标题】django cms 插件上的动态模型选择字段【英文标题】:Dynamic model choice field on a django cms plugin 【发布时间】:2017-07-11 21:09:51 【问题描述】:

我目前正在开发一个 django cms 插件,其模型选择字段依赖于表单中的另一个字段。 What i'm doing now via ajax is that, when the trigger field is selected, the dependent model choice field is updated via ajax to change the choices in the select field.但是在提交表单时,我遇到了这个错误

“选择一个有效的选项。这不是可用的选择之一。”

我在堆栈溢出中做了一些挖掘,发现了一个类似的问题

While using ajax with django form, getting error "Select a valid choice. That is not one of the available choices."

基于上面的链接,我应该根据我将从 request.POST 获得的触发器字段的值以插件本身的形式更新模型选择字段

我该如何为 django cms 插件执行此操作?我应该覆盖 cms 插件的哪个方法?我假设它是插件的 CMSPluginBase 类中的一个方法,但我不确定要覆盖什么方法,以及如何获得我的插件使用的当前表单,以便我可以在上述方法中覆盖它?

谢谢

【问题讨论】:

【参考方案1】:

经过一番挖掘,我能够通过覆盖表单的 is_valid() 过程中设置的字段查询来做到这一点

def is_valid(self):
    self.fields["my_field"].queryset=Foo.objects.filter(bar=baz)
    return super(MyForm, self).is_valid() 

这样,当表单的验证运行时,该字段已经被覆盖

【讨论】:

以上是关于django cms 插件上的动态模型选择字段的主要内容,如果未能解决你的问题,请参考以下文章

Django 动态模型字段

“渲染占位符”未出现在 django CMS 模板中

Django Admin 根据其他选择动态禁用字段

允许 Django 模型 ForeignKey 字段的表单上的 TextInput

将属性动态添加到 django 模型

django模型,如何动态设置查询的字段?