Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11523

Django process a form that dynamically adds fields, correct approach

Ive been reading about this in SO and I find the answers are kind of specific to the case that is being asked. My case is this one:

I need to create a form that represents a Receipt. Inside it, the user can dynamically add Items (In the backend, each Item has a FK to the Receipt the belong to).

So, should each Item be represented by a form? (each Item has several fields I'd like to validate on the backend) This means adding forms dynamically in the front ... and the forms added would be inside the "parent" form that represents the Receipt ... is this correct? How can I achieve that? how do I process it in the backend?

Or ... maybe I can just build the Html and Js without any relation to a Django form. Then on the backend, validate the fields "artifically" with bleach and try to figure out what data goes to the Receipt, how many Items where added and create the corresponding Items objects based on what I can read from cleaned_data... but this seems complex too.

Upvotes: 1

Views: 29

Answers (1)

mcastle
mcastle

Reputation: 2982

This is exactly what Django's inlineformset_factory and the django-dynamic-formsert package are made for. The inline formsets would represent the Items and each inline formset would be linked to a parent Receipt. See Inline Formsets for more info.

Upvotes: 2

Related Questions