Proper way to handle multiple forms on one page in Django

后端 未结 10 1989
既然无缘
既然无缘 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:46

    Wanted to share my solution where Django Forms are not being used. I have multiple form elements on a single page and I want to use a single view to manage all the POST requests from all the forms.

    What I've done is I have introduced an invisible input tag so that I can pass a parameter to the views to check which form has been submitted.

    <form method="post" id="formOne">
        {% csrf_token %}
       <input type="hidden" name="form_type" value="formOne">
    
        .....
    </form>
    
    .....
    
    <form method="post" id="formTwo">
        {% csrf_token %}
        <input type="hidden" name="form_type" value="formTwo">
       ....
    </form>
    

    views.py

    def handlemultipleforms(request, template="handle/multiple_forms.html"):
        """
        Handle Multiple <form></form> elements
        """
        if request.method == 'POST':
            if request.POST.get("form_type") == 'formOne':
                #Handle Elements from first Form
            elif request.POST.get("form_type") == 'formTwo':
                #Handle Elements from second Form
    
    0 讨论(0)
  • 2020-11-22 09:47

    You have a few options:

    1. Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.

    2. Read the submit button values from the POST data. You can tell which submit button was clicked: How can I build multiple submit buttons django form?

    0 讨论(0)
  • 2020-11-22 09:47

    Here is simple way to handle the above.

    In Html Template we put Post

    <form action="/useradd/addnewroute/" method="post" id="login-form">{% csrf_token %}
    
    <!-- add details of form here-->
    <form>
    <form action="/useradd/addarea/" method="post" id="login-form">{% csrf_token %}
    
    <!-- add details of form here-->
    
    <form>
    

    In View

       def addnewroute(request):
          if request.method == "POST":
             # do something
    
    
    
      def addarea(request):
          if request.method == "POST":
             # do something
    

    In URL Give needed info like

    urlpatterns = patterns('',
    url(r'^addnewroute/$', views.addnewroute, name='addnewroute'),
    url(r'^addarea/', include('usermodules.urls')),
    
    0 讨论(0)
  • 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
    <form action="" method="post">
        {% csrf_token %}
        {{ aform.as_p }}
        <input type="submit" name="{{aform.prefix}}" value="Submit" />
        {{ bform.as_p }}
        <input type="submit" name="{{bform.prefix}}" value="Submit" />
    </form>
    
    0 讨论(0)
提交回复
热议问题