views:

175

answers:

1

I am trying to populate a Django formset using data from a POST request. I am able to display the formset properly and instantiate it again mostly alright, but I'm having an issue where the formset is ending up with 2 blank rows at the end, which is undesirable. Below is the function we've been using in views.py:

forms.py

class DepositForm(forms.Form):
    InsID = forms.IntegerField()
    DepositTypeID = forms.IntegerField()
    DepositAmount = forms.IntegerField()
    Account = forms.IntegerField()

DepositFormSet = formset_factory(DepositForm, extra=1)

views.py

def _DepositEditor(request, c):
    if request.POST.has_key('form-0-InsID'):
        formset = DepositFormSet(request.POST)
        if formset.is_valid(): 
            formset = DepositFormSet(initial=formset.cleaned_data)
    else:
        formset = DepositFormSet()
    c['formset'] = formset

    return render_to_response('deposits/dep.html', c)

dep.html

<form action="" method="post">  

{{formset.management_form}}
{% for form in formset.forms %}
    {{form.errors }}
    {% for field in form %}
     {{field.label}}: {{field}}
    {% endfor %}
  <br />
{% endfor %}

<input type="submit" name="add" value="Add Deposit"></input>

</form>

That should be all the relevant code. Anyway, the template displays the whole formset, which should include a blank row (or, in the case of an error, no blank rows but error messages above the last row). The problem is occurring when you click "Add" with the last row blank. In the code, this still passes formset.is_valid(), so it then creates the new formset with an extra field. If you click add here, it returns with errors, but still allows you to fill out all but the last row and make a valid formset. Is there a way to tell my formset that blank forms should fail validation? Or alternatively is there better way to do this? The page eventually is planned to integrate some jquery stuff, so while that is not ideal, if there is a good way to solve this problem using jquery tools that would probably be good enough. Thanks a lot!

+1  A: 

In your views.py:

-            formset = DepositFormSet(initial=formset.cleaned_data)
+            data = formset.cleaned_data
+            if data[-1]=={}:
+                data=data[:-1]
+            formset = DepositFormSet(initial=data)

It's looks pretty much like a feature than like a bug ;)

Antony Hatchkins
That looks to have done it. Thanks a lot!
Jimmy McCarthy
You're welcome :)
Antony Hatchkins