Sometime it's critical to keep tracking who updated the records. Built-in CSV import function is great but doesn't update the field such as updated_on, updated_by fields. Here's how I solved the problem.
Let's create a sample app.
1. Create new app called "who_imports_csv"
2. Model - create db_tables.py
# coding: utf8 db.define_table('friends', Field('name'), Field('flag', length=1, default=""), Field('updated_by', update=auth.user.first_name + " " + auth.user.last_name if auth.user else None), Field('updated_on', 'datetime', update=request.now)) db.friends.updated_by.writable = False db.friends.updated_on.writable = False
Change titles on menu.py if you want.
response.title = "Who imports CSV ?" response.subtitle = "I know who you are"
3. Controller - replace index action with this
@auth.requires_login() def index(): if request.vars.csvfile != None: # set values table = db[request.vars.table] file = request.vars.csvfile.file # import csv file table.import_from_csv_file(file) # update who imported query = db.friends.flag=="" db(query).update(flag="1") response.flash = 'Data uploaded' return dict()
4. View - replace default/index.html with this
{{extend 'layout.html'}} {{=FORM(INPUT(_type='file',_name='csvfile'),INPUT(_type='hidden',_value='friends',_name='table'),INPUT(_type='submit',_value='Upload'))}}
5. Done !
6. Try importing the csv file
7. It's showing who/when updated.
Comments (1)
0
spametki 11 years ago
Great recipe. just wondering what's the connection with the slice thumbnail...