Proper way to handle multiple forms on one page in Django

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

    If you are using approach with class-based views and different 'action' attrs i mean

    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.

    You can easily handle errors from different forms using overloaded get_context_data method, e.x:

    views.py:

    class LoginView(FormView):
        form_class = AuthFormEdited
        success_url = '/'
        template_name = 'main/index.html'
    
        def dispatch(self, request, *args, **kwargs):
            return super(LoginView, self).dispatch(request, *args, **kwargs)
    
        ....
    
        def get_context_data(self, **kwargs):
            context = super(LoginView, self).get_context_data(**kwargs)
            context['login_view_in_action'] = True
            return context
    
    class SignInView(FormView):
        form_class = SignInForm
        success_url = '/'
        template_name = 'main/index.html'
    
        def dispatch(self, request, *args, **kwargs):
            return super(SignInView, self).dispatch(request, *args, **kwargs)
    
        .....
    
        def get_context_data(self, **kwargs):
            context = super(SignInView, self).get_context_data(**kwargs)
            context['login_view_in_action'] = False
            return context
    

    template:

    
    
    
    

提交回复
热议问题