Table of contents
1.
Introduction
2.
Storing the original filename
3.
autodelete
4.
Links to referencing records
5.
Pre-populating the form
6.
Frequently Asked Questions
6.1.
What is web2py?
6.2.
Why web2py?
6.3.
What is Database Abstraction Layer?
6.4.
What is API?
6.5.
What is meant by Pre populating?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Storing the original filename and pre populating the form in web2py

Author Sanchit Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Sometimes while using web2py, one might wonder where web2py keeps the original filename when downloaded, what happens upon deleting a record or is it possible to ensure that the file is deleted if the record is deleted, how to deal with situations where reference fields link tables and how to pre-populate a form.

web2py

To find answers to such questions, let us learn about storing the original filename, autodelete, links to referencing records and pre-populating the form in web2py.

Storing the original filename

When a file is downloaded, web2py automatically keeps the original filename inside the new UUID filename and retrieves it. The original filename is saved in the content-disposition header of the HTTP response after being downloaded. Everything is done transparently; there is no need for programming.

What happens when a file is downloaded.

On rare occasions, it could be useful to keep the original filename in a database field. In this situation, you must alter the model and provide a field to store it in:

db.define_table(p_'person',
    Field('n_name', requires=IS_NOT_EMPTY()),
    Field('img_image_fn_filename'),
    Field('img_image', 'upload'))
You can also try this code with Online Python Compiler
Run Code


The controller must then be adjusted to handle it:

def display_form():
    record = db.p_person(request.args(0)) or redirect(URL('index'))
    url = URL('download')
    form = SQLFORM(db.p_person, record, deletable=True,
                   upload=url, fields=['n_name', 'img_image'])
    if request.vars.img_image != None:
        form.vars.img_image_fn_filename = request.vars.img_image.fn_filename
    if form.process().accepted:
        response.flash = 'form -> accepted'
    elif form.errors:
        response.flash = 'form has -> errors'
    return dict(form=form)
You can also try this code with Online Python Compiler
Run Code
Notice

autodelete

Upon deleting a record, the SQLFORM does not delete the physical uploaded file(s) that the record references. This is because web2py does not know if the same file is used/linked by other tables or used for a different purpose. You can do the following when the corresponding record is deleted and you are certain if it is safe to delete the actual file:

db.define_table('img_image',
    Field('n_name', requires=IS_NOT_EMPTY()),
    Field('source', 'upload', autodelete=True))
You can also try this code with Online Python Compiler
Run Code


By default, the autodelete attribute is set to False. When it is set to True, it ensures that the file is deleted if the record is deleted.

Links to referencing records

Consider the situation when two tables are linked by a reference field.

For example -

db.define_table('p_person',
    Field('n_name', requires=IS_NOT_EMPTY()))
db.define_table('dog',
    Field('owner', 'reference person'),
    Field('n_name', requires=IS_NOT_EMPTY()))
db.dog.owner.requires = IS_IN_DB(db, 'p_person.id', '%(n_name)s')
You can also try this code with Online Python Compiler
Run Code


Given information:

  • A person has dogs
  • Each dog belongs to an owner
  • An owner is a person

The owner of dog is required to reference a valid db.p_person.id by '%(n_name)s'.
 

Let's add some people and their dogs using the appadmin interface for this application.

The appadmin UPDATE form displays a link to a page listing the dogs that belong to that person when editing an existing person. The SQLFORM's linkto argument can be used to simulate this behaviour. The URL of a new action that gets a query string from the SQLFORM and lists the related records must be pointed to by linkto.

For Example -

def display_form():
   record = db.p_person(request.args(0)) or redirect(URL('index'))
   link = URL('list_records', args='db')
   form = SQLFORM(db.p_person, record, deletable=True, linkto=link)
   if form.process().accepted:
       response.flash = 'form -> accepted'
   elif form.errors:
       response.flash = 'form has -> errors'
   return dict(form=form)
You can also try this code with Online Python Compiler
Run Code


Here is the page -

Output

"dog.owner" is a link by using the labels argument of the SQLFORM, the name of this link can be changed.

For example -

labels = {'dog.owner':"This person's -> dogs"}

On clicking the link (dog.owner), you will be redirected to:

/test/default/list_records/db/dog?query=db.dog.owner%3D%3D3


"list_records" is the specified action with 

  • request.args(0) set to the name of the referencing table
  • request.vars.query set to the SQL query string

The URL's query string contains the appropriately URL-encoded (when the URL is parsed, web2py decodes this automatically ) value "dog.owner==3."

The "list records" action can be easily implemented as follows:

def list_records():
    import re
    REGEX = re.compile(r'^(\w+).(\w+).(\w+)==(\d+)$')
    m_match = REGEX.m_match(request.vars.query)
    if not m_match:
        redirect(URL('error'))
    table, field, id = m_match.group(2), m_match.group(3), m_match.group(4)
    records = db(db[table][field]==id).select()
    return dict(records=records)
You can also try this code with Online Python Compiler
Run Code


with the accompanying "default/list_records.html" view:

{{extend 'layout.html'}}
{{=records}}
Note

Pre-populating the form

Pre-populating a form is always possible using the following syntax:

form.vars.name = 'field_value'

Regardless of whether the field (in this case, "name") is explicitly visualised in the form, statements like the one above must be added after the form declaration and before the form is accepted.

Frequently Asked Questions

What is web2py?

Web2py is a web application framework which is free and open-source, written in the Python programming language.

Why web2py?

Users can learn easily server-side web development, and it is lightweight and speedy.

What is Database Abstraction Layer?

A database abstraction layer is an API (Application Programming Interface) which unifies the communication between a computer application and databases such as Oracle, SQL Server, MySQL, IBM Db2 and PostgreSQL.

What is API?

API (Application Programming Interface) is a means of communication between two or more computer programs. It is a kind of software interface that provides a service to other software programs.

What is meant by Pre populating?

Pre populating means entering/filling in data in advance or, technically, populating form fields or databases in advance.

Conclusion

In this article, we discussed storing the original filename, autodelete attribute, links to referencing records and pre populating the form in web2py. We learnt where web2py keeps the original filename when downloaded, what happens upon deleting a record, what syntax to use to ensure that the file is deleted if the record is deleted, how to deal with situations where reference fields link tables and how to pre-populate a form.

To learn more about Web2Py, see Web2pyWeb2Py initWeb2py IntroductionWeb2Py InstallationTroubleshooting, and Application creation.

Nevertheless, you may consider our paid courses to give your career an edge over others.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Coding Ninjas
Live masterclass