Save the dynamically populated value on dropdown

徘徊边缘 提交于 2020-01-25 03:49:53

问题


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=[('', '------')]

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.

I can't use ForeignKey to populate subdomain because it depends from an external API service that we're using.

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.


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/50457498/save-the-dynamically-populated-value-on-dropdown

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