Django Forms - How to Use Prefix Parameter

25,568

Solution 1

You process each form as you normally would, ensuring that you create instances which have the same prefixes as those used to generate the form initially.

Here's a slightly awkward example using the form you've given, as I don't know what the exact use case is:

def some_view(request):
    if request.method == 'POST':
        form1 = GeneralForm(request.POST, prefix='form1')
        form2 = GeneralForm(request.POST, prefix='form2')
        if all([form1.is_valid(), form2.is_valid()]):
            pass # Do stuff with the forms
    else:
        form1 = GeneralForm(prefix='form1')
        form2 = GeneralForm(prefix='form2')
    return render_to_response('some_template.html', {
        'form1': form1,
        'form2': form2,
    })

Here's some real-world sample code which demonstrates processing forms using the prefix:

http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/

Solution 2

Even better, I think formsets is exactly what you're looking for.

class GeneralForm(forms.Form):
    field1 = forms.IntegerField(required=False)
    field2 = forms. IntegerField(required=False)

from django.forms.formsets import formset_factory

# GeneralSet is a formset with 2 occurrences of GeneralForm 
# ( as a formset allows the user to add new items, this enforces
#   2 fixed items, no less, no more )
GeneralSet = formset_factory(GeneralForm, extra=2, max_num=2)

# example view

def someview(request):
    general_set = GeneralSet(request.POST)
    if general_set.is_valid():
        for form in general_set.forms:
            # do something with data
    return render_to_response("template.html", {'form': general_set}, RequestContext(request))

You can even have a formset automatically generated from a model with modelformset_factory , which are used by the automated django admin. FormSet handle even more stuff than simple forms, like adding, removing and sorting items.

Share:
25,568

Related videos on Youtube

Greg
Author by

Greg

I'm an avid programmer, web developer and electronics enthusiast. Here's my gift to Python hackers. And you can see everything I'm up to here.

Updated on July 09, 2022

Comments

  • Greg
    Greg almost 2 years

    Say I have a form like:

    class GeneralForm(forms.Form):
        field1 = forms.IntegerField(required=False)
        field2 = forms. IntegerField(required=False)
    

    And I want to show it twice on a page within one form tag each time with a different prefix e.g.,:

    rest of page ...
    <form ..>
    GeneralForm(data,prefix="form1").as_table()
    GeneralForm(data,prefix="form2").as_table()
    <input type="submit" />
    </form>
    rest of page ...
    

    When the user submits this, how do I get the submitted form back into two separate forms to do validation, and redisplay it?

    This was the only documentation I could find and it's peckish.