How to wrap a Django Form Wizard in a View?

前端 未结 2 371
醉话见心
醉话见心 2021-01-06 05:33

This question is highly related to one that was previously asked and answered here: How wrap a FormWizard in a View?

Can someone post exact details of how they have

相关标签:
2条回答
  • 2021-01-06 06:01

    The as_view function converts a class based view into a callable view:

    myapp/views.py

    from django import forms
    from django.contrib.auth.decorators import login_required
    from django.contrib.formtools.wizard.views import SessionWizardView
    from django.template.response import TemplateResponse
    
    class Form1(forms.Form):
        a = forms.CharField()
    
    class Form2(forms.Form):
        b = forms.CharField()
    
    FORMS = [("step1", Form1),
             ("step2", Form2)]
    
    TEMPLATES = {"step1": "wizard_step.html",
                 "step2": "wizard_step.html"}
    
    class MyWizard(SessionWizardView):
    
        def get_template_names(self):
            return [TEMPLATES[self.steps.current]]
    
        def done(self, form_list):
            # get data from forms
            a = self.get_cleaned_data_for_step('step1')['a']
            b = self.get_cleaned_data_for_step('step2')['b']
            # access the request as self.request
            request = self.request
            # (...)
            # return response
            return TemplateResponse(request, 'wizard_success.html', {
                'a': a,
                'b': a
            })
    
    wizard_view = MyWizard.as_view(FORMS)
    
    @require_login
    def wrapped_wizard_view(request):
        return wizard_view(request)
    

    myapp/templates/wizard_step.html

    {% extends "base.html" %}
    {% load i18n %}
    
    {% block content %}
    
    <form method="post">
    {% include "formtools/wizard/wizard_form.html" %}
    </form>
    
    {% endblock %}
    

    myapp/urls.py

    from django.conf.urls import patterns, url
    
    urlpatterns = patterns('myapp.views',
        url(r'^wizard/$', 'wrapped_wizard_view'),
    )
    
    0 讨论(0)
  • 2021-01-06 06:08

    An alternative answer - instead of wrapping your view you could always use a decorator on your Wizardview class, as described in the documentation

    You would therefore do the following imports:

    from django.contrib.auth.decorators import login_required
    from django.utils.decorators import method_decorator
    

    and then within class createObjectWizard(SessionWizardView) you would add the following:

     @method_decorator(login_required)
     def dispatch(self, *args, **kwargs):
         return super(createObjectWizard, self).dispatch(*args, **kwargs)
    

    this way you don't have to mess with urls.py - it's all taken care of within the view. Hope this helps

    0 讨论(0)
提交回复
热议问题