Django - How can add multiple forms according to input enter number or with click add more button

I have an input field where the will customer add a number for buy membership then will get forms according to numbers 1,2, or 5 then will show 1,2, or 5 forms with input fields in which will add data.

How can add this type of functionality? Because I’m a beginner in python Django. Thanks

For example:

  1. customer will come to the site and click on buy membership
  2. the first page will How many Memberships do you want to buy? ==> input Field in which add 1,2, or 5
  3. based on how many members enter a show a page to collect information of members
  4. 3rd step collect customer/parent information

There are a couple of ways that come to mind. One, you could streamline the steps and just use a formset with up to 5 member information slots and analyze the response for the number of members. Two, you could have page #2 to get the number of memberships via a form and POST that, and then use that response to control another page by telling it how many form instances to display in a formset.

Regardless, it sounds like you need a formset of member info forms, so consult the Django formset documentation. Option one above would be the most common implementation. If it truly must be dynamic, probably the best option is the first one with some JavaScript on the page to add extra forms dynamically.

Thanks, Dear @jeremy.a.gray for replying to me. Sorry because I could not progress in a proper way but you got my problem. Please can you give me an example so that I will work on that with pure logic. Thanks

Firstly, welcome to the forums.

While we are primarily here to help people with their Free Code Camp progress, we are open to people on other paths, too. Some of what you are asking is pretty trivial in the Free Code Camp context, so you might find that if you’re not getting the instruction and material you need in your current studies, the FCC curriculum will really help you get started. At a modest guess I’d say investing a 4-5 hours working through the curriculum here will really pay off. You can find the curriculum at https://www.freecodecamp.org/learn.

With your current questions, we don’t have enough context to know what you already know or don’t know, so it is impossible to guide you without just telling you the answer (which we won’t do).

It is pretty typical on here for people to share a codepen / repl.it / jsfiddle example of what they have tried so that anyone helping has more of an idea of what help is actually helpful.

Please provide some example of what you’ve tried and I’m sure you’ll get more help.

Happy coding :slight_smile:

Thanks, Dear @JeremyLT for helping me.
Let me define with some code which I’m working on that.

I have reached the multiple forms adding by the user with the button. But my desire that on first page user will enter the number of form which he want then according to his number I will create the number of forms for him.

  1. Customers will come to the site and click on buy membership
    which I want…
  2. the first page will How many Memberships do you want to buy? ==> input Field in which add 1,2, or 5
    On that which I have worked with Django formsets you can see my code
    models.py
from django.db import models

class MemberShip(models.Model):
    GENDER = (
			('Male', 'Male'),
			('Female', 'Female'),
			)
    EXPERIENCE = (
			('First Time', 'First Time'),
			('Have skier and snowboard before', 'Have skier and snowboard before'),
			)
    first_name = models.CharField(max_length=200, null=True)
    last_name = models.CharField(max_length=200, null=True)
    experience = models.CharField(max_length=100, null=True, choices=EXPERIENCE)
    date_birth = models.CharField(max_length=20, null=True)
    gender = models.CharField(max_length=20, null=True, choices=GENDER)
    phone = models.CharField(max_length=20, null=True)
    
    def __str__(self):
      return self.first_name

forms.py

from django.forms import modelformset_factory
# from django.forms import ModelForm
from .models import MemberShip


MemberShipFormSet = modelformset_factory(
    MemberShip, fields=("first_name", "last_name", "experience", "date_birth", "gender", "phone"), extra=1
)

View.py

from django.views.generic import ListView, TemplateView
from .forms import MemberShipFormSet
from .models import MemberShip
from django.urls import reverse_lazy

class MemberShipList(ListView):
    model = MemberShip
    template_name = "customer/memberships_list.html"

class MemberShipAdd(TemplateView):
    template_name = "customer/memberships_add.html"

    def get(self, *args, **kwargs):
        formset = MemberShipFormSet(queryset=MemberShip.objects.none())
        return self.render_to_response({'membership_formset': formset})

    # Define method to handle POST request
    def post(self, *args, **kwargs):

        formset = MemberShipFormSet(data=self.request.POST)

        # Check if submitted forms are valid
        if formset.is_valid():
            formset.save()
            return redirect(reverse_lazy("member_ships_list"))

        return self.render_to_response({'membership_formset': formset})

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add MemberShip</title>
</head>
<body>
    <h1>Add a new MemberShip</h1>
    <form id="form-container" method="POST">
        {% csrf_token %}
        {{membership_formset.management_form}}
        {% for form in membership_formset %}
            <div class="membership-form">
                {{form.as_p}}
                <hr>
            </div>
        {% endfor %}
        <button id="add-form" type="button">Add Another MemberShip</button>
        <button type="submit">Create MemberShips</button>        
    </form>
    </body>

    <script>
        let membershipForm = document.querySelectorAll(".membership-form")
        let container = document.querySelector("#form-container")
        let addButton = document.querySelector("#add-form")
        let totalForms = document.querySelector("#id_form-TOTAL_FORMS")

        let formNum = membershipForm.length-1
        addButton.addEventListener('click', addForm)

        function addForm(e){
            e.preventDefault()

            let newForm = membershipForm[0].cloneNode(true)
            let formRegex = RegExp(`form-(\\d){1}-`,'g')

            formNum++
            newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`)
            container.insertBefore(newForm, addButton)
            
            totalForms.setAttribute('value', `${formNum+1}`)
        }
    </script>
</html>

Thanks in advance.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.