Search code examples
pythoncrudweb2pyweb2py-modules

how to create, insert and update database table using web2py?


I am new to python and web2py development. My requirement is :

I have to create one html page which consists Employee information for e.g. employee Name, Age, Address etc... and buttons will be there Save, Refresh ..after entering Employee info to the html page if user presses the Save button it should save the entry to Employee table(if it is already exists) OR it will first create the table and save the data into it, and click on Refresh button will fetch the data from data base Employee table and displays on the html page. web2py supports MVC architecture, so anyone please provide me the example code to how to achieve it using MVC in web2py.


Solution

  • In web2py you define your table structure in your model, something like this:

    # Sample Projects Container
    db.define_table('it_projects',
                    db.Field('project_name', 'string', length=255, required=True),
                    db.Field('description', 'text', required=False, default=''),
                    db.Field('is_active', 'boolean', required=False, default=True),
                    db.Field('created_on', 'datetime', required=True),
                    db.Field('created_by', db.auth_users),
                    db.Field('anonymous_read', 'boolean', required=True),
                    migrate='it_projects.table')
    

    Then you code your view containing your markup, and in your controller you just insert the data into the table, I'd suggest you read the online web2py book as it provides through information about CRUD operations. Cheers.