How to do a multi-step form in Django?

前端 未结 2 1024
小鲜肉
小鲜肉 2020-11-29 01:31

I would like to create a mutli-step form in Django that only submits the data for processing at the end of all the steps. Each step needs to be able to access and display da

2条回答
  •  误落风尘
    2020-11-29 01:59

    You can easily do this with the form wizard of django-formtools. A simple example would be something like the following.

    forms.py

    from django import forms
    
    class ContactForm1(forms.Form):
        subject = forms.CharField(max_length=100)
        sender = forms.EmailField()
    
    class ContactForm2(forms.Form):
        message = forms.CharField(widget=forms.Textarea)
    

    views.py

    from django.shortcuts import redirect
    from formtools.wizard.views import SessionWizardView
    
    class ContactWizard(SessionWizardView):
        def done(self, form_list, **kwargs):
            do_something_with_the_form_data(form_list)
            return redirect('/page-to-redirect-to-when-done/')
    

    urls.py

    from django.conf.urls import url
    
    from forms import ContactForm1, ContactForm2
    from views import ContactWizard
    
    urlpatterns = [
        url(r'^contact/$', ContactWizard.as_view([ContactForm1, ContactForm2])),
    ]
    

提交回复
热议问题