2

Hey guys, I know this question has been brought up numerous times, but I'm not quite getting the full implementation. As you can see below, I've got a form that I can dynamically tell how many rows to create. How can I create an "Add Row" link that tells the view how many rows to create? I would really like to do it without augmenting the url...

# views.py
def myView(request):
    if request.method == "POST": 
        form = MyForm(request.POST, num_rows=1)

        if form.is_valid():
            return render_to_response('myform_result.html', context_instance=RequestContext(request))
    else:
        form = MyForm(num_rows=1)

    return render_to_response('myform.html', {'form':form}, context_instance=RequestContext(request))


# forms.py
class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        num_rows = kwargs.pop('num_rows',1)
        super(MyForm, self).__init__(*args, **kwargs)

        for row in range(0, num_rows):
            field = forms.CharField(label="Row")
            self.fields[str(row)] = field


# myform.html  http://example.com/myform
<form action="." method="POST" accept-charset="utf-8">
    <ul>
        {% for field in form %}
            <li style="margin-top:.25em">
                <span class="normal">{{ field.label }}</span> 
                {{ field }}
                <span class="formError">{{ field.errors }}</span>
            </li>
        {% endfor %}
    </ul>
    <input type="submit" value="Save">
</form>
<a href="ADD_ANOTHER_ROW?">+ Add Row</a>

2 Answers 2

11

When you have a form with a variable number of rows, what you need is a formset.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, I knew it was something I probably hadn't gotten into before. Thanks for steering me in the right direction! Besides formsets working better than what I was doing, the ManagementForm is the part I was looking for.
0

11 years later!!!

I wanted to add a -not-so-important flag to the form dynamically without creatig a specific form for this task. Here's how i handled my case

class CreateFooView(generic.CreateView):  
   ... 
   def get_form(self, form_class=None):
       form = super().get_form(form_class=self.form_class)
       ...
       field = forms.BooleanField(label="Add to Bar",required=False)
       form.fields['add_to_bar'] = field
       return form

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.