Hi I have a site which outputs a user results as a table of parts and quantities. User interaction on the page can result in a variable number of rows (parts) in the table.
I need to save this list of parts against the user, so I believe formsets are the best way to handle this:
forms.py
class UserBuildForm(forms.Form):
part = forms.CharField()
part_quantity = forms.IntegerField()
views.py
from django.forms.formsets import formset_factory
from tool.forms import UserBuildForm
def my_view(request):
...
UserBuildFormSet = formset_factory(UserBuildForm)
formset = UserBuildFormSet()
...
My idea is to wrap the form fields in the table html so that a parts column and quantity column are actually inputs (though only the quantity should be user-editable). This way each row is actually a form.
Now, my ajax function works by appending and removing rows to the table.Can I add extra form fields as just plain html?
How should I handle these dynamic number of forms? I know you can specify the number of formsets using extra but the number of forms I will need to validate are unknown.
Also - is this the best approach to this typical method of saving user product data?
Any help much appreciated.
Just iterate over forms in views.py to handle data:
for form in formset.forms: form.save()
Here is excellet tutorial, which show you how to handle with adding/deleting form fields (jquery): http://stellarchariot.com/blog/2011/02/dynamically-add-form-to-formset-using-javascript-and-django/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With