1

What is the best way to handle a page with multiple forms and an unknown number of elements in one of the forms?

Lets suppose I have 3 models, Book, Recipe and Ingredient and these need to be displayed on the same web page. Each Book can also hold any number of Recipes and each Recipe can hold any number of Ingredients. Each of these models will also have a form that inherits from ModelForm.

Once the form is displayed to the user, she is free to dynamically add as many Recipes or Ingredients a she needs. This is to be done via JS with no Ajax.

What is the best way to handle this when validating forms? Validating the form for Book is easy but how do I handle the unknown number of Recipes and Ingredients?

ruipacheco
  • 15,025
  • 19
  • 82
  • 138

1 Answers1

1

The solution is to use prefixes and numbers. So a form will have the prefix 'recipe_1_' and each ingredient in the recipe will have the prefix 'ingredient_1_'.

For the second recipe and second set of ingredients just up the integer.

When submitting the form it's necessary to get the values from request.form and use them to create a form one by one, usually by looping through the content of request.form and using the prefix to decide which Form to use.

Community
  • 1
  • 1
ruipacheco
  • 15,025
  • 19
  • 82
  • 138