Django Forms - How to Use Prefix Parameter

后端 未结 2 1467
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-24 07:30

Say I have a form like:

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


        
2条回答
  •  一整个雨季
    2020-12-24 08:12

    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/

提交回复
热议问题