Table of contents
1.
Introduction 
2.
SQLFORM in web2py
3.
Process and Validate Methods
3.1.
Model
3.2.
View
3.3.
Controller
4.
Frequently Asked Questions 
4.1.
What is the purpose of web2py?
4.2.
Describe SQLForm.
4.3.
How does web2py differs from Django?
4.4.
How can I run web2py?
4.5.
What purpose does SQLForm serve?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

What is SQLFORM in web2py?

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

Introduction 

Web developers can use Python to program dynamic web content with Web2py. Although a web developer can still build a form from scratch if required, Web2py helps in reducing tedious web development tasks, such as creating web forms from scratch. 

What is SQLform in web2py

To know more about web2py you can follow these links- What is web2py? and web2py introduction.

For form generation, web2py comes with powerful functions. The following are four different ways to build forms in web2py:

ways to build forms in web2py

Now that we have understood the use of web2py and different ways to build forms, it’s time to install Web2Py. To install Web2Py you can refer to this link- Web2Py Installation. Whereas for creating a new Web2py Application you can follow this link- Create application. In this blog we will discuss SQLFORM in web2py in detail-

SQLFORM in web2py

SQLForm in web2py helps in the creation of a form for the existing database. Multiple applications can be served by the web2py instance. Every application has a controller (default.py) where you may enter your Python code and a view, which creates an HTML page for user interaction.

MVC Structure

Let’s just concentrate on models, controllers, and views for now. The developer must separate data representation (model), data presentation (view), and application workflow (controller), according to web2py.

A web server receives a request from a user interacting with a web2py application through a browser and forwards it to a controller. The controller decides what should be done. Typically, it communicates with the model and reads from and writes to the database. After that, the controller renders a view using the information from the model and delivers it back to the browser.

Steps for mvc patterns

SQLFORM provides a high-level API for building, creating, updating and deleting the forms from an existing database table.

Process and Validate Methods

If we want to write

form.accepts(request.post_vars, session, ...)
You can also try this code with Online Python Compiler
Run Code


then its shortcut is,

form.process(...).accepted
You can also try this code with Online Python Compiler
Run Code

The request and session parameters are not required for the latter (although you can specify them optionally). It differs from accepted further in that it gives the form back. Process calls accept and transmit their arguments to one another internally. Accepts returns a value that is saved in form.accepted.

The process function accepts an additional parameter that it does not take, but it does take:

  • onsuccess: If this value is equal to "flash" (the default) and the form is accepted, the message onsuccess will flash.
  • onfailure: If the value of onfailure is equal to "flash" (the default), when the form's validation fails, the message onfailure will flash.
  • next: Specifies where to direct the user after the form has been submitted.
     

Functions like lambda form: do_something((form)) can be used for onsuccess and onfailure.

You can write 

form.process(..., dbio = False).accepted
You can also try this code with Online Python Compiler
Run Code


as

form.validate(...)
You can also try this code with Online Python Compiler
Run Code

 

Web2py is designed to guide a web developer using the Model View Controller (MVC) pattern. Let us take a close look at each of these patterns.

Model

What is a Model?

The model is a layer of the application that contains the data logic. Data from the database is retrieved and stored using the objects in the model. Database Abstraction Layer (DAL), an API included with Web2py, converts Python objects into database objects including queries, tables, and records.

View

web2py utilises Python for its models, controllers, and views, albeit the views employ a slightly modified Python syntax to enable for more understandable code without placing any constraints on appropriate Python usage.

A view's aim is to embed Python code in an HTML document. 

Controller

Let's understand controller

The controller is a layer of the application that manages user interaction. Controllers can read data from views, control user input, and sends input data for a particular model.

The model communicates with the Controller and creates the database connection with the database. On the other side, the Controller works with the View to create the data display.

 

Let us now start with implementing a SQLForm:-

SQLForm facilitates the development of a form in Web2py for the current database. The procedures for putting it into practice are outlined below.

DAL( Database Abstraction Layer) object, also known as the DAL constructor, is used to build the connection with the database. The user can build the appropriate table once the connection has been made.

db = DAL('sqlite://storage.sqlite')
db.define_table('ninjas', 
Field('name', 'email','course','numberofcourse')
You can also try this code with Online Python Compiler
Run Code


As a result, we have made a table called "ninjas". 

With the help of the following statements, the controller creates the form and button:

form = SQLFORM(
  db.mytable,
  record = mytable_index,
  deletable = True,
  submit_button = T('Update')
)
You can also try this code with Online Python Compiler
Run Code


As a result, the controller would need to be modified as follows for the created ninjas table:

def index():
    form = SQLFORM(db.ninjas)
You can also try this code with Online Python Compiler
Run Code


The view has not changed at all. Since the SQLFORM constructor created one from the table db.ninjas defined in the model, creating a FORM in the new controller is required. When serialized, the new form looks like this:

 

<!DOCTYPE html>
  <html>
    <head>
      <title>Web2py SQLFORM</title>
    </head>
    
    <body>
      <h2>Welcome To Coding Ninjas</h2>
      <form>
        <p>
          <label>Username : <input type="text" id="username" /></label>
        </p>
        <p>
          <label>Email : <input type="email" id="email" /></label>
        </p>
        <p>
          <label>Course : <input type="text" id="course" /></label>
        </p>
        <p>
          <label>Number of Courses : <input type="number" id="numbercourse" /></label>
        </p>
        <p>
          <button type="submit" id="submitbtn">Submit</button>
        </p>
      </form>
    </body>
  </html>

 

Output:

By storing uploaded files in the "uploads" folder, an SQLFORM object also handles "upload" fields. The process is automatic. Checkboxes and text values with the aid of "textareas" are used by SQLFORM to show "Boolean" values.

Also utilizing the process approach is SQLFORM.

This is required if the user wants to save values with an accompanying SQLFORM.

It is acceptable if form.process(keepvalues = True).

 

The SQLFORM constructor allows various customizations, such as displaying only a subset of the fields, changing the labels, adding values to the optional third column, or creating UPDATE and DELETE forms, as opposed to INSERT forms like the current one. SQLFORM is the single biggest time-saver object in web2py.

For more information  visit this link- SQLForm and insert/update/delete in web2pySqlForm grid signatureSqlformsmartgrid-in-web2py and Extra form elements and sqlform without database io in web2py

Now, let us discuss some FAQs based on the above discussion.

faqs

Frequently Asked Questions 

What is the purpose of web2py?

Web developers can use Python to program dynamic web content with the help of Web2py. Although a web developer can still create a form from scratch if necessary, Web2py is designed to help reduce tedious web development tasks, such as developing web forms from scratch.

Describe SQLForm.

When the form is accepted, SQLFORM creates a new record to the database. The form becomes a UPDATE form for the record you pass as the optional second argument to the SQLFORM constructor. This indicates that no new record is inserted when the form is submitted; instead, the existing record is updated.

How does web2py differs from Django?

Because it is smaller, easy to learn, and doesn't have project-level configuration files, web2py differs from Django. Compared to PHP-based frameworks and Java-based frameworks, web2py has a much clearer syntax than PHP-based frameworks and less verbose than Java-Based frameworks. This makes applications easier to read, maintain, and develop.

How can I run web2py?

Web2py doesn't need to be installed. Start by running the corresponding web2py file after unzipping the downloaded zip file for your specific operating system. Attention: Mark Hammond's win32 extensions must first be installed in order to run web2py on Windows from source.

What purpose does SQLForm serve?

The existing database can be created, updated, and deleted with the help of SQLFORM.

Conclusion

To conclude the discussion, we’ve extensively looked at SQLFORM in web2py, where we’ve looked upon the different ways to build forms in web2py. Next, you will also get the idea of the MVC pattern system in web2py. Lastly, we’ve also discussed some frequently asked questions.

We hope this article has helped you in understanding What is SQLFORM in web2py, but the knowledge never stops. Have a look at more related articles:Web2pyPrepare the toolsTroubleshooting Use CasesCapacity Planning Use Testcases and many more.

Refer to our carefully curated articles and videos and code studio library if you want to learn more. Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Learning!

Live masterclass