Table of contents
1.
Introduction
2.
Form Generation
3.
SQLFORM.factory
3.1.
Uploading files with SQLFORM.factory
3.1.1.
One form for multiple tables
3.1.2.
Confirmation Forms
3.1.3.
Form to edit a dictionary
4.
Frequently Asked Questions
4.1.
Is web2py worth learning?
4.2.
What is the use of web2py?
4.3.
Is web2py an MVC model?
4.4.
Does web2py support Python 3?
4.5.
Which is better, web2py or Flask?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Other types of Forms in web2py

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A portion of a page known as a form includes controls including text fields, password fields, checkboxes, radio buttons, a submit button, menus, etc. A form makes it easier for the user to input data like name, email address, password, phone number, etc., and that data will transfer to the server for processing. web2py handles forms uniquely, which involves powerful functions responsible for form generation.

web2py intro image

There are four ways we can create forms in web2py- FORM, SQLFORM, SQLFORM.factory, and CRUD Methods. In the following article, we will dive deeper into other types of forms and look at their usage along with examples.

Form Generation

A simple form can be generated with the helpers like the FORM object.

lets learn image

Controller

The below function in “default.py” controller includes FORM object (HTML helper) which helps in creation of form.

def display_form():
#function to display form   
   form = FORM('Value:', INPUT(_value = 'name'), INPUT(_type = 'submit'))
   return dict(form = form)
You can also try this code with Online Python Compiler
Run Code


View

The form which is generated by the statement {{= form}} serializes the FORM object.
{{extend 'layout.html'}}
<h2>Basic form</h2>
{{= form}}
<h2>Submitted variables</h2>
{{= BEAUTIFY(request.vars)}}
You can also try this code with Online Python Compiler
Run Code


The form self-submits when a user fills it out and hits the submit button, and the variable request.vars.value and its input value are displayed at the bottom.

SQLFORM.factory

Without a database, the user may occasionally need to create a form using an existing database table. The user merely wishes to benefit from the SQLFORM functionality.

This is accomplished via form.factory, and a session is kept.

def form_from_factory():
   form = SQLFORM.factory(
      Field('your_name', requires = IS_NOT_EMPTY()),
      Field('your_image', 'upload'))
      
   if form.process().accepted:
      response.flash = 'form accepted'
      session.your_name = form.vars.your_name
      session.your_image = form.vars.your_image
   elif form.errors:
      response.flash = 'form has errors'


   return dict(form = form)
You can also try this code with Online Python Compiler
Run Code


The form will look like an SQLFORM with fields for name and image, but there isn't a database table with such names.

The view for "default/form from factory.html" will look like this-

{{extend 'layout.html'}}
{{= form}}
You can also try this code with Online Python Compiler
Run Code

Uploading files with SQLFORM.factory

There are the following three ways we can upload files with SQLFORM.factory namely-

  1. One form for multiple tables
  2. Confirmation forms
  3. Form to edit A dictionary 

One form for multiple tables

It frequently happens that you wish to develop a single form that allows users to enter information about one customer and their default address but you already have two tables, such as "client" and "address," connected together by a reference. 

model:

db.define_table('client',
     Field('name'))
db.define_table('address',
    Field('client', 'reference client',
          writable=False, readable=False),
    Field('street'), Field('city'))
You can also try this code with Online Python Compiler
Run Code


controller:

def register():form1 = SQLFORM.factory(db.client, db.address)
    if form1.process().accepted:
        id1 = db.client.insert(**db.client._filter_fields(form1.vars))
        form1.vars.client = id1
        id1 = db.address.insert(**db.address._filter_fields(form1.vars))
        response.flash = 'Thanks for filling the form'
    return dict(form1=form1)
You can also try this code with Online Python Compiler
Run Code


Take note of SQLFORM.factory (it makes ONE form using public fields from both tables and inherits their validators too). When a form is submitted, this performs two inserts of data—some into one table and some into the other.

Confirmation Forms

You frequently require a form with a confirmation option. If the option is selected, the form should be accepted—but only after submission. Additional options on the form may link to other websites. There is an easy way to achieve this with web2py-

form = FORM.confirm('Are you sure?')
if form.accepted: do_what_needs_to_be_done()
You can also try this code with Online Python Compiler
Run Code


Keep in mind that since this is handled internally, the confirm form does not require and cannot call.accepts or.process. The confirmation form allows you to add buttons with links in the form of a dictionary of { "value": "link"}-

form = FORM.confirm('Are you sure?', {'Back':URL('other_page')})
if form.accepted: do_what_needs_to_be_done()
You can also try this code with Online Python Compiler
Run Code


Form to edit a dictionary

Consider a system where configuration options are kept in a dictionary,

config = dict(color='black', language='English')
You can also try this code with Online Python Compiler
Run Code


additionally, you must have a form to enable visitors to edit this dictionary. This is possible with-

form = SQLFORM.dictform(config)
if form.process().accepted: config.update(form.vars)
You can also try this code with Online Python Compiler
Run Code


Each entry from the dictionary will have its own INPUT field on the form. Dictionary keys will be used as INPUT names, labels, and current values to deduce kinds (string, int, double, date, datetime, boolean).

This works excellent, but I'll leave the reasoning behind making the configuration dictionary persistent to you. For instance, you could want to keep the configuration in a session.

if not session.config:
    session.config = dict(color='black', language='English')
form = SQLFORM.dictform(session.config)
if form.process().accepted:
session.config.update(form.vars)
You can also try this code with Online Python Compiler
Run Code

Frequently Asked Questions

Is web2py worth learning?

Web2py is a top-notch framework, yes. The simplicity of usage, from installation to learning to code to distribution to deployment, is a key objective of web2py.

What is the use of web2py?

Python dynamic web content programming is made possible via Web2py. Web2py is made to make laborious web development jobs more manageable, such as creating web forms from scratch, while a web developer can still do it if necessary.

Is web2py an MVC model?

The Ruby on Rails and Django frameworks inspired the creation of web2py. Web2py is similar to these frameworks in that it emphasizes rapid development, prefers convention over configuration, and adheres to the model-view-controller (MVC) architectural pattern.

Does web2py support Python 3?

Web2py functions on Python 2.7 and Python 3 along with CPython (the C implementation) and PyPy (Python written in Python).

Which is better, web2py or Flask?

The majority of the Slant community suggests Flask when comparing web2py to that framework. What are the best backend web frameworks, as in the question? Web2py is ranked 19th, while Flask is placed fourth.

Conclusion

In this article, we have extensively discussed types of Forms in web2py. We began with a brief introduction to forms followed by their types and examples. 

After reading about  Other types of Forms in web2py, refer to the web2py web framework,

Also check out - Data Dictionary In Software Engineering

What is web2py web frameworkweb2py introductionweb2py installationCreating a New Web2Py ApplicationWeb2Py - Prepare the ToolWeb2Py - Troubleshooting Use Cases, and Web2Py - Capacity Planning Use CasesApplication development using PythonIntroduction to Python- Coding Ninjas for a deeper understanding of web2py development and other related topics.

Thank you image
Live masterclass