Django: Can class-based views accept two forms at a time?

前端 未结 7 2386
说谎
说谎 2020-11-29 17:50

If I have two forms:

class ContactForm(forms.Form):
    name = forms.CharField()
    message = forms.CharField(widget=forms.Textarea)

class SocialForm(forms         


        
7条回答
  •  孤街浪徒
    2020-11-29 18:21

    By default, class-based views only support a single form per view. But there are other ways to accomplish what you need. But again, this cannot handle both forms at the same time. This will also work with most of the class-based views as well as regular forms.

    views.py

    class MyClassView(UpdateView):
    
        template_name = 'page.html'
        form_class = myform1
        second_form_class = myform2
        success_url = '/'
    
        def get_context_data(self, **kwargs):
            context = super(MyClassView, self).get_context_data(**kwargs)
            if 'form' not in context:
                context['form'] = self.form_class(request=self.request)
            if 'form2' not in context:
                context['form2'] = self.second_form_class(request=self.request)
            return context
    
        def get_object(self):
            return get_object_or_404(Model, pk=self.request.session['value_here'])
    
        def form_invalid(self, **kwargs):
            return self.render_to_response(self.get_context_data(**kwargs))
    
        def post(self, request, *args, **kwargs):
            self.object = self.get_object()
            if 'form' in request.POST:
                form_class = self.get_form_class()
                form_name = 'form'
            else:
                form_class = self.second_form_class
                form_name = 'form2'
    
            form = self.get_form(form_class)
    
            if form.is_valid():
                return self.form_valid(form)
            else:
                return self.form_invalid(**{form_name: form})
    

    template

    {% csrf_token %} .........
    {% csrf_token %} .........

提交回复
热议问题