Home > Software engineering >  Every form validation in formset
Every form validation in formset

Time:10-31

Some troubles with validation.

I'm using this construction in my template:

<form method="POST">
{% csrf_token %}
{{ formset.media.js }}
{% for form in formset %}
<p>{{ form }}</p>
{% endfor %}


<button type="submit" >Send</button>

And this validation in views:

def flow_type(request):

patternFormset = modelformset_factory(CashFlowPattern, fields='__all__')

if request.method == 'POST':
    formset = patternFormset(request.POST)
    if formset.is_valid():
        formset.save()

formset = patternFormset()

template = 'cash_table/index.html'
context = {
    # 'form': form,
    'formset': formset
}
return render(request, template, context)

I get form at page but nothing happens after submit.

But if I use another template construction it works:

<form method="POST">
{% csrf_token %}
{{ formset.media.js }}
{{ formset }}
    
    
<button type="submit" >Send</button>
</form>

But then I get all fields of new form at the same line.

CodePudding user response:

I think you need to have {{ formset.management_form }} in the template where you iterate through the forms of the formset so that Django knows that it is a formset, and knows how many forms are in the formset, etc...

<form method="POST">
{% csrf_token %}

{{ formset.management_form }}

{{ formset.media.js }}
{% for form in formset %}
<p>{{ form }}</p>
{% endfor %}


<button type="submit" >Send</button>

When you use {{ formset }} the management is done automatically (it's a shortcut).

Source: https://docs.djangoproject.com/en/4.1/topics/forms/formsets/#custom-formset-validation

  • Related