Thiru
Thiru

Reputation: 3373

Using formset_factory in Django

I'm a new user to Django, i use the following code to produce a form

class GetMachine(forms.Form):
    Machine_Name = forms.CharField(max_length=20) 
    Number_of_lines = forms.IntegerField(max_value=10)

class GetLine(forms.Form):
    Line_name = forms.CharField(max_length=20)

def install(request):
    if request.method == 'POST':
        form = GetMachine(request.POST) 
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            form = GetLine()
            return render_to_response('install.html', { 'form': form, })
    else:
        form = GetMachine() # An unbound form

    return render_to_response('install.html', { 'form': form, })    

How can modify the above code, such that the "Number_of_lines" is used to create n number of "Line_Name" form fields.

For example, if the value of Number_of_lines is 2, I would again like to ask the user to enter the name of both the lines as

Name of Line-1:

Name of Line-2:

Upvotes: 4

Views: 3986

Answers (1)

Richard Jelte
Richard Jelte

Reputation: 304

After you get the number_of_lines from the POST data, you can pass that number as the 'extra' parameter to the formset factory.

from django.forms.formsets import formset_factory
...
        form = GetMachine(request.POST) 
        if form.is_valid(): # All validation rules pass
            number_of_lines = form.cleaned_data['Number_of_lines']

            GetLineFormSet = formset_factory(GetLine, extra=number_of_lines)
            formset = GetLineFormset()
            form = GetLine()
...

Protip: You can also use the max_num parameter to keep the number of lines to a reasonable limit:

GetLineFormSet = formset_factory(GetLine, extra=number_of_lines, max_num=10)

Upvotes: 6

Related Questions