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

前端 未结 7 2377
说谎
说谎 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:36

    Use django-superform

    This is a pretty neat way to thread a composed form as a single object to outside callers, such as the Django class based views.

    from django_superform import FormField, SuperForm
    
    class MyClassForm(SuperForm):
        form1 = FormField(FormClass1)
        form2 = FormField(FormClass2)
    

    In the view, you can use form_class = MyClassForm

    In the form __init__() method, you can access the forms using: self.forms['form1']

    There is also a SuperModelForm and ModelFormField for model-forms.

    In the template, you can access the form fields using: {{ form.form1.field }}. I would recommend aliasing the form using {% with form1=form.form1 %} to avoid rereading/reconstructing the form all the time.

提交回复
热议问题