[Django]-Conditional Logic in django forms

5👍

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.

👤tatlar

Leave a comment