Question

I have a django page with two forms:

class FooForm(forms.Form):
    number = forms.CharField(
        label = "Number",
    )
    num_forms = forms.CharField(
        label = "Num Forms"
    )
...

class BarForm(forms.Form):
    name = forms.CharField(
        label = "Name",
    )
...

One is to be displayed as a single form, and the other as a formset:

def myview(request):
        ...
        num_forms = request.GET['num_forms'])
        formsetFactory = formset_factory(BarForm, extra = num_forms)
        formset = formsetFactory()
        return render(request, 'template.html', {'form': FooForm(user), 'formset':formset, 'num_forms':num_forms)

I'm using django-crispy-forms for setting layout and have rendered them in template.html like so:

<form action="{% url myview %}" class="form-horizontal" method="post">
        {% crispy form %}
        {% if num_forms and num_forms > 0 %}
            {% crispy formset formset.form.helper %}
        {% endif %}
 </form>

The behavior I desire: A field in form specifies the number of forms in formset to display, so on update of that field formset reloads with that many forms displayed. The other field data in form should not be cleared or modified. Validation can be run, but I'd like the option to control when that happens.

Can someone guide me on how to implement my view and/or template to make this work? Thanks!

Was it helpful?

Solution

You can reload the values by passing back FooForm on response rendering:

form = FooForm(request.POST)
...
return render(request, 'template.html', {'form': form})

Not sure how to pass back without validating (or clearing the validation before returning), though

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top