Conditional Logic in django forms

白昼怎懂夜的黑 提交于 2019-12-07 23:12:12

问题


I'm trying to build a conditional form where selecting one option will cause a new field to appear underneath, while selecting another option will display something else.

Formstack has a good example https://www.formstack.com/features/conditional-logic

I couldn't find any preexisting form packages for django with this functionality. How should I start implementing this?


回答1:


Django forms (especially if you use the ModelForm library) are a direct reflection of your Django application Model. You should therefore start by refactoring your Django application Model to have fields that have optional values (i.e. they can be NULL, empty or have a default value already created).

These would be the form fields that are shown/hidden based on your conditional(s) and they may or may not have values (if they are hidden based on a conditional it is impossible to provide a value to them so the Model fields must be able to accept NULL values or use the defaults).

You would then use a client-side language such as Javascript (JS) to handle the user iteraction with your Django application. A simple to use JS framework like jQuery would be worthwhile investigating for your needs.

In addition to the exceptional Django docs on Forms, I also highly recommend you take a look at Django Crispy Forms writtten by PyDanny to see how Django forms should be done right.



来源:https://stackoverflow.com/questions/31418350/conditional-logic-in-django-forms

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