"""A reaction to Jacob's post: http://jacobian.org/writing/dynamic-form-generation/ """ from webob.dec import wsgify from webob import exc from webob import Response from tempita import HTMLTemplate from formencode import htmlfill page_template = HTMLTemplate(''' Register
{{for index, question in enumerate(questions)}} {{endfor}}
''', name='page') def get_questions(req): return ['how old are you?'] + req.GET.getall('question') def save_answer(req, question, value): print 'Answer %s: %s' % (question, value) @wsgify def questioner(req): if req.path_info == '/thanks': return Response('Thanks!') questions = get_questions(req) errors = {} if req.method == 'POST': errors = validate(req, questions) if not errors: for question in questions: save_answer(req, question, req.POST[question]) raise exc.HTTPFound(location='/thanks') page = page_template.substitute( action=req.url, questions=questions) page = htmlfill.render( page, defaults=req.params, errors=errors) return Response(page) def validate(req, questions): errors = {} form = req.POST if (form.get('password') and form['password'] != form.get('password_confirm')): errors['password_confirm'] = 'Passwords do not match' fields = questions + ['username', 'password'] for field in fields: if not form.get(field): errors[field] = 'Please enter a value' return errors if __name__ == '__main__': from paste.httpserver import serve serve(questioner)