Debian Codegraph @

docs/source/simple_forms_processing.rst

raw
1 .. _simple_forms_processing:
2
3 Example Application: Simple Forms Processing
4 ============================================
5
6 This guide will walk you through building a simple Pecan web application that will do some simple forms processing.
7
8 Project Setup
9 -------------
10
11 First, you'll need to install Pecan:
12
13 ::
14
15 $ pip install pecan
16
17 Use Pecan's basic template support to start a new project:
18
19 ::
20
21 $ pecan create mywebsite
22 $ cd mywebsite
23
24 Install the new project in development mode:
25
26 ::
27
28 $ python setup.py develop
29
30 With the project ready, go into the ``templates`` folder and edit the ``index.html`` file. Modify it so that it resembles this:
31
32 .. code-block:: html
33
34 <%inherit file="layout.html" />
35
36 <%def name="title()">
37 Welcome to Pecan!
38 </%def>
39 <header>
40 <h1><img src="/images/logo.png" /></h1>
41 </header>
42 <div id="content">
43 <form method="POST" action="/">
44 <fieldset>
45 <p>Enter a message: <input name="message" /></p>
46 <p>Enter your first name: <input name="first_name" /></p>
47 <input type="submit" value="Submit" />
48 </fieldset>
49 </form>
50 % if not form_post_data is UNDEFINED:
51 <p>${form_post_data['first_name']}, your message is: ${form_post_data['message']}</p>
52 % endif
53 </div>
54
55 **What did we just do?**
56
57 #. Modified the contents of the ``form`` tag to have two ``input`` tags. The first is named ``message`` and the second is named ``first_name``
58 #. Added a check if ``form_post_data`` has not been defined so we don't show the message or wording
59 #. Added code to display the message from the user's ``POST`` action
60
61 Go into the ``controllers`` folder now and edit the ``root.py`` file. There will be two functions inside of the ``RootController`` class which will display the ``index.html`` file when your web browser hits the ``'/'`` endpoint. If the user puts some data into the textbox and hits the submit button then they will see the personalized message displayed back at them.
62
63 Modify the ``root.py`` to look like this:
64
65 .. code-block:: python
66
67 from pecan import expose
68
69
70 class RootController(object):
71
72 @expose(generic=True, template='index.html')
73 def index(self):
74 return dict()
75
76 @index.when(method='POST', template='index.html')
77 def index_post(self, **kwargs):
78 return dict(form_post_data=kwargs)
79
80 **What did we just do?**
81
82 #. Modified the ``index`` function to render the initial ``index.html`` webpage
83 #. Modified the ``index_post`` function to return the posted data via keyword arguments
84
85 Run the application:
86
87 ::
88
89 $ pecan serve config.py
90
91 Open a web browser: `http://127.0.0.1:8080/ <http://127.0.0.1:8080/>`_
92
93 Adding Validation
94 -----------------
95
96 Enter a message into the textbox along with a name in the second textbox and press the submit button. You should see a personalized message displayed below the form once the page posts back.
97
98 One problem you might have noticed is if you don't enter a message or a first name then you simply see no value entered for that part of the message. Let's add a little validation to make sure a message and a first name was actually entered. For this, we will use `WTForms <http://wtforms.simplecodes.com/>`_ but you can substitute anything else for your projects.
99
100 Add support for the `WTForms <http://wtforms.simplecodes.com/>`_ library:
101
102 ::
103
104 $ pip install wtforms
105
106 .. note::
107
108 Keep in mind that Pecan is not opinionated when it comes to a particular library when working with form generation, validation, etc. Choose which libraries you prefer and integrate those with Pecan. This is one way of doing this, there are many more ways so feel free to handle this however you want in your own projects.
109
110 Go back to the ``root.py`` files and modify it like this:
111
112 .. code-block:: python
113
114 from pecan import expose, request
115 from wtforms import Form, TextField, validators
116
117
118 class PersonalizedMessageForm(Form):
119 message = TextField(u'Enter a message',
120 validators=[validators.required()])
121 first_name = TextField(u'Enter your first name',
122 validators=[validators.required()])
123
124
125 class RootController(object):
126
127 @expose(generic=True, template='index.html')
128 def index(self):
129 return dict(form=PersonalizedMessageForm())
130
131 @index.when(method='POST', template='index.html')
132 def index_post(self):
133 form = PersonalizedMessageForm(request.POST)
134 if form.validate():
135 return dict(message=form.message.data,
136 first_name=form.first_name.data)
137 else:
138 return dict(form=form)
139
140 **What did we just do?**
141
142 #. Added the ``PersonalizedMessageForm`` with two textfields and a required field validator for each
143 #. Modified the ``index`` function to create a new instance of the ``PersonalizedMessageForm`` class and return it
144 #. In the ``index_post`` function modify it to gather the posted data and validate it. If its valid, then set the returned data to be displayed on the webpage. If not valid, send the form which will contain the data plus the error message(s)
145
146 Modify the ``index.html`` like this:
147
148 .. code-block:: html
149
150 <%inherit file="layout.html" />
151
152 ## provide definitions for blocks we want to redefine
153 <%def name="title()">
154 Welcome to Pecan!
155 </%def>
156 <header>
157 <h1><img src="/images/logo.png" /></h1>
158 </header>
159 <div id="content">
160 % if not form:
161 <p>${first_name}, your message is: ${message}</p>
162 % else:
163 <form method="POST" action="/">
164 <div>
165 ${form.message.label}:
166 ${form.message}
167 % if form.message.errors:
168 <strong>${form.message.errors[0]}</strong>
169 % endif
170 </div>
171 <div>
172 ${form.first_name.label}:
173 ${form.first_name}
174 % if form.first_name.errors:
175 <strong>${form.first_name.errors[0]}</strong>
176 % endif
177 </div>
178 <input type="submit" value="Submit">
179 </form>
180 % endif
181 </div>
182
183 .. note::
184
185 Keep in mind when using the `WTForms <http://wtforms.simplecodes.com/>`_ library you can customize the error messages and more. Also, you have multiple validation rules so make sure to catch all the errors which will mean you need a loop rather than the simple example above which grabs the first error item in the list. See the `documentation <http://wtforms.simplecodes.com/>`_ for more information.
186
187 Run the application:
188
189 ::
190
191 $ pecan serve config.py
192
193 Open a web browser: `http://127.0.0.1:8080/ <http://127.0.0.1:8080/>`_
194
195 Try the form with valid data and with no data entered.