Proper way to handle multiple forms on one page in Django

后端 未结 10 2011
既然无缘
既然无缘 2020-11-22 09:19

I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:

if request.method == \'POST\':
    form = Au         


        
10条回答
  •  长发绾君心
    2020-11-22 09:49

    I needed multiple forms that are independently validated on the same page. The key concepts I was missing were 1) using the form prefix for the submit button name and 2) an unbounded form does not trigger validation. If it helps anyone else, here is my simplified example of two forms AForm and BForm using TemplateView based on the answers by @adam-nelson and @daniel-sokolowski and comment by @zeraien (https://stackoverflow.com/a/17303480/2680349):

    # views.py
    def _get_form(request, formcls, prefix):
        data = request.POST if prefix in request.POST else None
        return formcls(data, prefix=prefix)
    
    class MyView(TemplateView):
        template_name = 'mytemplate.html'
    
        def get(self, request, *args, **kwargs):
            return self.render_to_response({'aform': AForm(prefix='aform_pre'), 'bform': BForm(prefix='bform_pre')})
    
        def post(self, request, *args, **kwargs):
            aform = _get_form(request, AForm, 'aform_pre')
            bform = _get_form(request, BForm, 'bform_pre')
            if aform.is_bound and aform.is_valid():
                # Process aform and render response
            elif bform.is_bound and bform.is_valid():
                # Process bform and render response
            return self.render_to_response({'aform': aform, 'bform': bform})
    
    # mytemplate.html
    
    {% csrf_token %} {{ aform.as_p }} {{ bform.as_p }}

提交回复
热议问题