1
|
|
|
"""A simple multi-step wizard that uses the flask application session. |
2
|
|
|
|
3
|
|
|
Creating multi-step forms of arbitrary length is simple and intuitive. |
4
|
|
|
|
5
|
|
|
Example usage: |
6
|
|
|
|
7
|
|
|
``` |
8
|
|
|
from flask.ext.wtf import FlaskForm |
9
|
|
|
|
10
|
|
|
class MultiStepTest1(FlaskForm): |
11
|
|
|
field1 = StringField(validators=[validators.DataRequired()],) |
12
|
|
|
field2 = StringField(validators=[validators.DataRequired()],) |
13
|
|
|
|
14
|
|
|
|
15
|
|
|
class MultiStepTest2(FlaskForm): |
16
|
|
|
field3 = StringField(validators=[validators.DataRequired()],) |
17
|
|
|
field4 = StringField(validators=[validators.DataRequired()],) |
18
|
|
|
|
19
|
|
|
|
20
|
|
|
class MyCoolForm(MultiStepWizard): |
21
|
|
|
__forms__ = [ |
22
|
|
|
MultiStepTest1, |
23
|
|
|
MultiStepTest2, |
24
|
|
|
] |
25
|
|
|
``` |
26
|
|
|
""" |
27
|
|
|
|
28
|
|
|
from flask import session |
29
|
|
|
from flask.ext.wtf import FlaskForm |
30
|
|
|
|
31
|
|
|
|
32
|
|
|
class MultiStepWizard(FlaskForm): |
33
|
|
|
"""Generates a multi-step wizard. |
34
|
|
|
|
35
|
|
|
The wizard uses the app specified session backend to store both |
36
|
|
|
form data and current step. |
37
|
|
|
|
38
|
|
|
TODO: make sure all the expected features of the typical form |
39
|
|
|
are exposed here, but automatically determining the active form |
40
|
|
|
and deferring to it. See __iter__ and data for examples. |
41
|
|
|
""" |
42
|
|
|
|
43
|
|
|
__forms__ = [] |
44
|
|
|
|
45
|
|
|
def __iter__(self): |
46
|
|
|
"""Get the specific forms' fields for standard WTForm iteration.""" |
47
|
|
|
_, form = self.get_active() |
48
|
|
|
return form.__iter__() |
49
|
|
|
|
50
|
|
|
def __init__(self, *args, **kwargs): |
51
|
|
|
"""Do all the required setup for managing the forms.""" |
52
|
|
|
super(MultiStepWizard, self).__init__(*args, **kwargs) |
53
|
|
|
# Store the name and session key by a user specified kwarg, |
54
|
|
|
# or fall back to this class name. |
55
|
|
|
self.name = kwargs.get('session_key', self.__class__.__name__) |
56
|
|
|
# Get the sessions' current step if it exists. |
57
|
|
|
curr_step = session.get(self.name, {}).get('curr_step', 1) |
58
|
|
|
# if the user specified a step, we'll use that instead. Form validation |
59
|
|
|
# will still occur, but this is useful for when the user may need |
60
|
|
|
# to go back a step or more. |
61
|
|
|
if 'curr_step' in kwargs: |
62
|
|
|
curr_step = int(kwargs.pop('curr_step')) |
63
|
|
|
if curr_step > len(self.__forms__): |
64
|
|
|
curr_step = 1 |
65
|
|
|
self.step = curr_step |
66
|
|
|
# Store forms in a dunder because we want to avoid conflicts |
67
|
|
|
# with any WTForm objects or third-party libs. |
68
|
|
|
self.__forms = [] |
69
|
|
|
self._setup_session() |
70
|
|
|
self._populate_forms() |
71
|
|
|
invalid_forms_msg = 'Something happened during form population.' |
72
|
|
|
assert len(self.__forms) == len(self.__forms__), invalid_forms_msg |
73
|
|
|
assert len(self.__forms) > 0, 'Need at least one form!' |
74
|
|
|
self.active_form = self.get_active()[1] |
75
|
|
|
# Inject the required fields for the active form. |
76
|
|
|
# The multiform class will always be instantiated once |
77
|
|
|
# on account of separate POST requests, and so the previous form |
78
|
|
|
# values will no longer be attributes to be concerned with. |
79
|
|
|
self._setfields() |
80
|
|
|
|
81
|
|
|
def _setfields(self): |
82
|
|
|
"""Dynamically set fields for this particular form step.""" |
83
|
|
|
_, form = self.get_active() |
84
|
|
|
for name, val in vars(form).items(): |
85
|
|
|
if repr(val).startswith('<UnboundField'): |
86
|
|
|
setattr(self, name, val) |
87
|
|
|
|
88
|
|
|
def alldata(self, combine_fields=False, flush_after=False): |
89
|
|
|
"""Get the specific forms data.""" |
90
|
|
|
_alldata = dict() |
91
|
|
|
# Get all session data, combine if specified, |
92
|
|
|
# and delete session if specified. |
93
|
|
|
if self.name in session: |
94
|
|
|
_alldata = session[self.name].get('data') |
95
|
|
|
if combine_fields: |
96
|
|
|
combined = dict() |
97
|
|
|
for formname, data in _alldata.items(): |
98
|
|
|
if data is not None: |
99
|
|
|
combined.update(data) |
100
|
|
|
_alldata = combined |
101
|
|
|
if flush_after: |
102
|
|
|
self.flush() |
103
|
|
|
return _alldata |
104
|
|
|
|
105
|
|
|
@property |
106
|
|
|
def data(self): |
107
|
|
|
"""Get the specific forms data.""" |
108
|
|
|
_, form = self.get_active() |
109
|
|
|
return form.data |
110
|
|
|
|
111
|
|
|
@property |
112
|
|
|
def forms(self): |
113
|
|
|
"""Get all forms.""" |
114
|
|
|
return self.__forms |
115
|
|
|
|
116
|
|
|
def _setup_session(self): |
117
|
|
|
"""Setup session placeholders for later use.""" |
118
|
|
|
# We will populate these values as the form progresses, |
119
|
|
|
# but only if it doesn't already exist from a previous step. |
120
|
|
|
if self.name not in session: |
121
|
|
|
session[self.name] = dict( |
122
|
|
|
curr_step=self.curr_step, |
123
|
|
|
data={f.__name__: None for f in self.__forms__}) |
124
|
|
|
|
125
|
|
|
def _populate_forms(self): |
126
|
|
|
"""Populate all forms with existing data for validation. |
127
|
|
|
|
128
|
|
|
This will only be done if the session data exists for a form. |
129
|
|
|
""" |
130
|
|
|
# We've already populated these forms, don't do it again. |
131
|
|
|
if len(self.__forms) > 0: |
132
|
|
|
return |
133
|
|
|
for form in self.__forms__: |
134
|
|
|
data = session[self.name]['data'].get(form.__name__) |
135
|
|
|
init_form = form(**data) if data is not None else form() |
136
|
|
|
self.__forms.append(init_form) |
137
|
|
|
|
138
|
|
|
def _update_session_formdata(self, form): |
139
|
|
|
"""Update session data for a given form key.""" |
140
|
|
|
# Add data to session for this current form! |
141
|
|
|
name = form.__class__.__name__ |
142
|
|
|
data = form.data |
143
|
|
|
# Update the session data for this particular form step. |
144
|
|
|
# The policy here is to always clobber old data. |
145
|
|
|
session[self.name]['data'][name] = data |
146
|
|
|
|
147
|
|
|
@property |
148
|
|
|
def active_name(self): |
149
|
|
|
"""Return the nice name of this form class.""" |
150
|
|
|
return self.active_form.__class__.__name__ |
151
|
|
|
|
152
|
|
|
def next_step(self): |
153
|
|
|
"""Set the step number in the session to the next value.""" |
154
|
|
|
next_step = session[self.name]['curr_step'] + 1 |
155
|
|
|
self.curr_step = next_step |
156
|
|
|
if self.name in session: |
157
|
|
|
session[self.name]['curr_step'] += 1 |
158
|
|
|
|
159
|
|
|
@property |
160
|
|
|
def step(self): |
161
|
|
|
"""Get the current step.""" |
162
|
|
|
if self.name in session: |
163
|
|
|
return session[self.name]['curr_step'] |
164
|
|
|
|
165
|
|
|
@step.setter |
166
|
|
|
def step(self, step_val): |
167
|
|
|
"""Set the step number in the session.""" |
168
|
|
|
self.curr_step = step_val |
169
|
|
|
if self.name in session: |
170
|
|
|
session[self.name]['curr_step'] = step_val |
171
|
|
|
|
172
|
|
|
def validate_on_submit(self, *args, **kwargs): |
173
|
|
|
"""Override validator and setup session updates for persistence.""" |
174
|
|
|
# Update the step to the next form automagically for the user |
175
|
|
|
step, form = self.get_active() |
176
|
|
|
self._update_session_formdata(form) |
177
|
|
|
if not form.validate_on_submit(): |
178
|
|
|
self.step = step - 1 |
179
|
|
|
return False |
180
|
|
|
# Update to next form if applicable. |
181
|
|
|
if step - 1 < len(self.__forms): |
182
|
|
|
self.curr_step += 1 |
183
|
|
|
self.active_form = self.__forms[self.curr_step - 1] |
184
|
|
|
self.next_step() |
185
|
|
|
# Mark the current step as -1 to indicate it has been |
186
|
|
|
# fully completed, if the current step is the final step. |
187
|
|
|
elif step - 1 == len(self.__forms): |
188
|
|
|
self.step = -1 |
189
|
|
|
return True |
190
|
|
|
|
191
|
|
|
@property |
192
|
|
|
def remaining(self): |
193
|
|
|
"""Get the number of steps remaining.""" |
194
|
|
|
return len(self.__forms[self.curr_step:]) + 1 |
195
|
|
|
|
196
|
|
|
@property |
197
|
|
|
def total_steps(self): |
198
|
|
|
"""Get the number of steps for this form in a (non-zero index).""" |
199
|
|
|
return len(self.__forms) |
200
|
|
|
|
201
|
|
|
@property |
202
|
|
|
def steps(self): |
203
|
|
|
"""Get a list of the steps for iterating in views, html, etc.""" |
204
|
|
|
return range(1, self.total_steps + 1) |
205
|
|
|
|
206
|
|
|
def get_active(self): |
207
|
|
|
"""Get active step.""" |
208
|
|
|
form_index = self.curr_step - 1 if self.curr_step > 0 else 0 |
209
|
|
|
return self.curr_step + 1, self.__forms[form_index] |
210
|
|
|
|
211
|
|
|
def flush(self): |
212
|
|
|
"""Clear data and reset.""" |
213
|
|
|
del session[self.name] |
214
|
|
|
|
215
|
|
|
def is_complete(self): |
216
|
|
|
"""Determine if all forms have been completed.""" |
217
|
|
|
if self.name not in session: |
218
|
|
|
return False |
219
|
|
|
# Make the current step index something unique for being "complete" |
220
|
|
|
completed = self.step == -1 |
221
|
|
|
if completed: |
222
|
|
|
# Reset. |
223
|
|
|
self.curr_step = 1 |
224
|
|
|
return completed |
225
|
|
|
|