Generating forms based on user choices in Django

I am working on a Django project whose purpose is to allow the user to fill in some forms. In some of these forms, the user must make a choice between several options and, based on the choice made, a particular form must be generated. At the end of all these forms, the data entered must be used to write a pdf file.

As for the functionality related to generating the pdf, what I'm interested in for the purposes of the question is the use of data entered in one view in another view using them as context.

Here's what I tried to do.

First of all I created some forms in

class ChoiceForm(forms.Form):
    CHOICES = [
        ('1', 'Choice-One'),
        ('2', 'Choice Two'),
    choice = forms.ChoiceField(choices=CHOICES)

class ChoiceOneForm(forms.Form):
    name_one = forms.CharField(max_length=200)

class ChoiceTwoForm(forms.Form):
    name_two = forms.CharField(max_length=200)

Then I created this view in

def contact(request):
    if request.method == 'POST':
        num_people = int(request.POST.get('num_people'))
        people_formset = [forms.ChoiceForm() for i in range(num_people)]
        return render(request, 'home.html', {'people_formset': people_formset})
        return render(request, 'home.html')

def generate_pdf(request):
    context = {}
    return render(request, 'pdf.html', context)

And finally I have this HTML file called 'home.html':

    <form method="post">
        {% csrf_token %}
        People number: <input type="number" name="num_people" required>
        <input type="submit" value="Submit">
    {% if people_formset %}
        {% for form in people_formset %}
                {% csrf_token %}
                {{ form.as_p }}
                <input type="submit" value="Submit">
        {% endfor %}
    {% endif %}

what I've been able to achieve so far is to generate as many 'choice' fields as the value of the number entered in the 'num_people' field.

What I'm missing is:

1. Being able to create, for each 'choiche' field in the formset, a ChoiceOneForm or ChoicheTwoForm form based on the choice made in the 'choice' field;

2. Being able to use all this data in the 'generate_pdf' view (for now what interests me is being able to include this data in the context of this view).

Back to Top