问题描述
我正在使用适用于Django的wagtail CMS,我想为下拉列表添加一个动态填充的值,并将其保存在Page模型中,这是我的代码:
I'm using wagtail CMS for Django, I want to add a dynamically populated value for a dropdown and save it on the Page model, this is my code:
class MyPage(Page):
domain = CharField(max_length=10, choices=MY_CHOICES)
subdomain = CharField(max_length=10, choices=[('', '------')]
我有一些前端逻辑可以动态填充子域的选项,但是在我点击保存后,我得到了:The page could not be created due to validation errors
在子域字段中:Select a valid choice. [my value] is not one of the available choices.
I've got some frontend logic to populate dynamically the options for subdomain, but after I hit save I got: The page could not be created due to validation errors
And in the subdomain field: Select a valid choice. [my value] is not one of the available choices.
我不能使用ForeignKey填充子域,因为它取决于我们正在使用的外部API服务.
I can't use ForeignKey to populate subdomain because it depends from an external API service that we're using.
我试图使用从CharField
继承的自定义字段,但没有成功,它看起来仅对domain
字段执行validate
方法.
I tried to use a custom field that inherits from CharField
with no success, it looks it executes validate
method only for the domain
field.
推荐答案
如果使用choices
参数,则必须预先定义可能值的列表.阅读 docs 的相关部分(最后该部分的两个段落.
If you use the choices
argument, you have to predefine the list of possible values. Read the relevant part of the docs (last two paragraphs of that section).
您可以从模型字段定义中省略choices
参数,而仅在前端呈现HTML select
标记(然后按照您的说明动态地填充选项).
You could omit the choices
argument from the model field definition and only render a HTML select
tag in the frontend (which is then filled with options dynamically, like you explained).
您还可以考虑将CharField
的默认小部件更改为select
标记,例如此答案和这部分文档显示.
You could also look into changing the default widget of the CharField
to a select
tag, like this answer and this part of the docs show.
这篇关于在下拉菜单中保存动态填充的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!