首页 > 解决方案 > How do I create a Django form that allows for user to enter their own value for "other" radio option

问题描述

I have a Model in Django called VolunteerOpportunity that has an attribute called event_name. I'd like the event_name attribute to be a foreign key to another table where the app admins can create default event names such as Career Fair, Senior Bingo, PAWS, etc. I'd also like there to be an "Other" option, that when selected, a user can type in his/her own value. I'd like that value to be stored, however, I don't want it to show up for users as an option the next time the form is loaded.

I've attached an example of what I'd like, but this is done through Google Forms.

Google Form example

How should I structure the Model(s) and form to allow for such a structure?

标签: djangodjango-modelsdjango-forms

解决方案


马上,我发现了这个。请注意,这篇文章已有四年之久 - 但一般原则仍应适用:

创建自定义小部件子类化 MultiWidget

此小部件将单选小部件与MultiWidget.widgets属性中“其他选择”的文本输入小部件组合在一起。您必须实现该decompress方法;顾名思义,该方法用于将存储在数据库中的单个值转换为多个值,这些值应与self.widgets.
我怀疑链接文章中描述的正确呈现小部件的方式仍然适用于较新的 django 版本(例如forms.RadioSelect.renderer不再存在),因此您将不得不自己进行一些修补。

创建自定义字段子类MultiValueField

与上面的自定义小部件非常相似,此表单字段将 (Model)ChoiceField 和“其他选项”CharField 组合成一个实体。此自定义字段必须实现该compress方法 - 与小部件的方法互补decompress。的返回值compress用于验证、清理和保存。

制作一个使用自定义字段代替默认表单字段的自定义表单

(不言自明)

配置模型的字段选择或动态地将选择分配给表单

如果您的默认选项列表非常静态,您可以在模型上定义它(如文章中所示)。否则,您可以在form.__init__. 无论哪种方式,您都应该将“其他选项”附加到默认选项列表中。


如果这太麻烦了,您可以考虑使用还允许创建新记录/选择的选择字段的实现:django-select2django-autocomplete-light。或者也许已经有这样一个领域,因为我怀疑你是第一个想要那个功能的人。


推荐阅读