1

How can I make an "Add another ____" button for a rendered formset?

I've noticed people go about this using jQuery (Dynamically adding a form to a Django formset with Ajax)

The django polls tutorial does not really explain how the "Add another Choice" link is generated in the admin. (https://docs.djangoproject.com/en/1.6/intro/tutorial02/)

How can I reuse that same functionality in my templates, views & forms?

Here is some of my code.

forms.py

class StudentForm(forms.ModelForm):
    # The last 15 years.
    thisYear = int(time.strftime("%Y"))
    farAway = thisYear-15
    years = []
    for y in range(farAway,thisYear):
        years.append(str(y))

    birth_date = forms.DateField(widget=SelectDateWidget(years=tuple(years)))
    class Meta:
        model = Student
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_action = ''

        self.helper.add_input(Submit('submit', 'Submit'))
        super(StudentForm, self).__init__(*args, **kwargs)

add-students.html

<h2>Add Students</h2>
    {% for f in StudentFormSet %}
        {% crispy f %}
    {% endfor %}

views.py

def addStudents(request):
    StudentFormSet = formset_factory(StudentForm, can_delete=True, extra=3)
    if request.method == 'POST':
        formset = StudentFormSet(request.POST)
        if formset.is_valid():
            saved = formset.save(commit=False)
            saved.save()
            messages.success(request, "Submitted! Thank you.")
    else:
        formset = StudentFormSet()
    return render_to_response('add-students.html', 
                                locals(),
                                context_instance=RequestContext(request))
Community
  • 1
  • 1
broinjc
  • 2,619
  • 4
  • 28
  • 44
  • 1
    That is exactly correct.. read the post you linked. You can generate an empty formset via {{ formset.empty_form }} which has convenient placeholders for javascript to replace. https://docs.djangoproject.com/en/dev/topics/forms/formsets/#empty-form – Yuji 'Tomita' Tomita Feb 15 '14 at 04:44

0 Answers0