3

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!

2 Answers 2

2

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 looks pretty much like a feature than like a bug ;)

Sign up to request clarification or add additional context in comments.

Comments

1

I've not done this myself, but if you wanted to actually make it invalid with a blank entry, perhaps you'd consider putting it in the clean method:

http://docs.djangoproject.com/en/dev/topics/forms/formsets/#custom-formset-validation

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.