I’m using standard Django Model Forms which are then used in HTML templates for an application system we’re currently re-jigging.
The tricky bit (for me at least) is one step in the process which dynamically adds additional forms to the HTML using a jQuery plugin called “SheepIt” and I’m wondering how all the form data can be easily collected in the related view.
The SheepIt bit:
$(document).ready(function() {
var sheepItForm = $('#sheepItForm').sheepIt({
separator: '',
allowRemoveLast: true,
allowRemoveCurrent: true,
allowRemoveAll: false,
allowAdd: true,
allowAddN: false,
minFormsCount: 1,
iniFormsCount: 1
});
});
Template code:
<div id="entry_form">
<form method="post" enctype="multipart/form-data" action="/enter/2/" id="sheepItForm">
<fieldset id="sheepItForm_template">
<a id="sheepItForm_remove_current">X</a>
<div class="select">{{ form.select }}</div>
<div class="text">{{ form.text }}</div>
<div class="upload">{{ form.upload }}</div>
</fieldset>
<div id="sheepItForm_noforms_template">No Entries</div>
<div id="sheepItForm_controls">
<div id="sheepItForm_add"><a><strong>+</strong> Add Another Entry</a></div>
</div>
{{ formset.management_form }}
<input type="submit" value="Proceed to Payment">
</form></div>
The above outputs a little form with buttons to add and remove clones of the form using the SheepIt plugin.
Normally, we would collect the form data with something like:
form_data = request.POST.copy()
Or similar. Should I just iterate over everything collected in the post data or is there a better perhaps ‘pythonic’ way of handling these little clones? Perhaps gathering them into a formset then doing something similar to:
for f in formset.forms:
if f.is_valid():
f.save()
Edit:
And here’s some of the views code that I’m currently chopping and changing:
form = EntryForm_2_set.form()
template_dict['form'] = form
if request.method == 'POST':
# from forms.py: EntryForm_2_set = forms.formsets.formset_factory(EntryForm_2, extra=0)
formset = EntryForm_2_set(request.POST)
if formset.is_valid():
for f in formset.forms:
if f.is_valid():
f.save()
entry_url = reverse('entry-stage',kwargs={'stage':3})
return HttpResponseRedirect(entry_url)
else:
formset = EntryForm_2_set()
template_dict['formset'] = formset
return render_to_response('submission-stage-two.html', template_dict, RequestContext(request))
Any ideas guys?
Managed to sort it out myself eventually.
Only thing that remains is filling the forms upon re-entry.
The thing that I was missing before was the implementation of the formset factory with its flexibility. If there’s a more elegant solution I’d be interested to hear suggestions for future updates.
Cheers guys.
View code:
Template code: