[Answered ]-Django: Switch a form in template depending on choice field

1👍

How I’d tackle it. Write 4 forms. One, with a single ChoiceField. The other 3, to get the appropriate inputs for damage types 1 to 3 as chosen in the first. Display all the forms in your template:

<form> {% csrf_token %}
  {{damage_type_form.as_p}}

  <div id="type1">
     {{damage_form_1.as_p}}
  </div>
  <div id="type2">
     {{damage_form_2.as_p}}
  </div>
  <div id="type3">
     {{damage_form_3.as_p}}
  </div>

  <input type="submit" ...>
</form>

(obviously, pass the four forms in your context, as you’d normally pass just one)

In your view POST processing, you will use the damage_type to determine which form is to be validated and used. Bind all four forms (to request.POST), then use the choice to decide which one gets validated and used. Ignore the other two.

(This may be the first time I’ve actually thought that a Function-based view will probably be easier than using the Class-Based Views)

Finally, write some JS that will hide the <div>s that are not selected in the damage_type pulldown/ ChoiceField.

Leave a comment