Python and Web: Building Dynamic Web Forms in Web2Py from Ground – Part I

Sep 3, 2012
Python
By

Accept it.

Under the particular domain of web development, Python has offered much more than we expected it to in the early 2000’s. It now offers multiple pre-built web frameworks that even a novice coder can utilize for the development of complex applications. Today, we will witness it. Today, we will go through the process of building a dynamic web form using one of its frameworks called Web2Py on a local machine/server.

In the progression of this tutorial, you will be able to learn how dynamic web forms are created, how their field validation schemes work, and how easily they are linked with the database under the hood of Web2Py. This tutorial (however) assumes that:

  1. You have a working Python (2.7+) distribution installed.
  2. You have downloaded Web2Py server (preferably .zip) on your machine.
  3. You are familiar with the basic concepts of web forms.

Let’s go.

Starting the Server:

In order to start your Web2Py server, cd to the unzipped web2py folder using command line and type:

> web2py.exe localhost:8000 --password [your new password]

You will see a notification message once you hit enter after typing this command. At this point, verify the server initiation by typing http://localhost:8000 in your browser and if you see a welcome page, you are good to go forward.

Creating Form Application:

Browse to the administrative interface on the Web2Py welcome page and create a new application from the right hand section and name it as forms. We will use this application to experiment with our dynamic web form. Now, at this point, you need to understand some basics. The application you just created in Web2Py has only major file (for now) that you need to be concerned of in order to experiment with the web form, which is default.py in the Controller section. This default.py is a Python controller that constructs the back-end operations for your form application and manages the data provided by it.

Building Form:

Begin with the construction of your web form by opening up the default.py file (in the edit mode) and define a new database scheme as follows (at the end of the file):

db = DAL('sqlite://storage.sqlite')
db.define_table('registration',
    Field('firstname', requires=IS_NOT_EMPTY()),
    Field('lastname', requires=IS_NOT_EMPTY()),
    Field('gender', requires=IS_IN_SET(['Male', 'Female'])),
    Field('username', requires=IS_NOT_EMPTY()),
    Field('password', 'password'),
    Field('about_you', 'text'),
    Field('image', 'upload'))

Once this default.py is saved, Web2Py controller reads this database schema, and based on that, constructs a table named ‘registration’ having the following fields:

  1. firstname
  2. lastname
  3. gender
  4. username
  5. password
  6. about_you

The first line in the above code (db = DAL(‘sqlite://storage.sqlite’) defines the database abstraction layer (DAL()) for the Web2Py controller, and based on the input parameters provided, it establishes the connection with the defined database. Since SQLite comes by default with Web2Py, so we will utilize it (although this can be replaced by any type of DBMS like MySQL, etc.). On the other hand, the function right below it (db.define_table()) defines the structure of the newly created database table.

Once you are there, now its time to create the form fields. In the same default.py, enter this new function at the end of the file (right below the database code):

def form_a():
    form = SQLFORM(db.registration)
    return dict(form=form)

You have just created a nice looking registration form using the SQLFORM() function in Web2Py, which simply extracts all the input fields defined in the ‘registration’ table (isn’t it cool?). All you need to do now is to call it all in an html template/page.

Calling the Form:

In the Views section of the forms application page, create a new html file named default/form_a.html (it is recommended that you keep the html file name as default/[name of the function] that you specified in default.py). Open this newly created html file and make it read like this:

<h5> User Registration Form </h5>
<br  />
{{=form}}
<br  />

This is it! Browse to http://127.0.0.1:8000/forms/default/form_a.html to see your handy work.

So-called ‘Dynamism’:

Alright, lets add some ‘dynamism’ to our web form so that it notifies the user about what fields are mandatory and additionally, shows the submitted data to the user. To do so, make your form_a() function look something like this:

def display_form():
    form = SQLFORM(db.registration)
    if form.process().accepted:
        response.flash = ‘You have successfully submitted the form’
    elif form.errors:
        response.flash = 'Please check your form for errors'
    else:
        response.flash = 'This form cannot be left empty!'
    return dict(form=form)

Reload the html page to see the notification tweaks we just added.

Conclusion:

The process is very simple: We define the database table with all its fields (using db.define_table()) and call these fields into the Web2Py’s form through a separate Python function, which constructs them as form input fields. Once we have the form fields ready to be published, we import them on a new/existing html ‘views’ template by simply calling the form function under the html tags.

In the next article of this series, we will talk about some more advanced features for these web forms (just to give you a hint) like database validation, custom field creation, database update/delete/insert functions and few other cool functions – all using Web2Py’s Pythonic powers!

Author: Saifuddin Abdullah
Saifuddin Abdullah is a tech writer and a Python based desktop/web applications developer working from New York City. His key areas of interest include mining, illustration and statistical evaluation of raw data using multiple programming applications.
  • Robert, F.

    Excellent approach..actually I am surprised since I have always used Django but now I see that web2py has a lot more to offer as well. waiting for the next piece.

  • alanb

    Nice tutorial, thanks. View page needs to include {{ extend ‘layout.html’ }} to display flash messages, and ‘def display_form():’ should be ‘def form_a’.

    • marcos

      Thanks too.

  • thomas

    Rather typical republican political response. Obstruct first,
    ask questions later.

  • Muhammad Ahmed

    Wonderful Tutorial….!