File download - disable link when no files are available

50 views
Skip to first unread message

P T

unread,
Feb 27, 2015, 12:45:03 PM2/27/15
to web...@googlegroups.com
Hello All,

Currently using Web2Py 2.8.2-stable+timestamp.2013.11.28.13.54.07

I have a simple page for announcing seminars and for downloading presentation files.

Here are definitions for table, controller and view :


db.define_table("seminars",
               
Field('sem_date', 'date', label='Date'),
               
Field('Sem_Time', 'string', label='Time'),
               
Field('room', 'string', label='Location'),
               
Field('person', 'string', label='Presenter'),
               
Field('title', 'string', label='Seminar Title'),
               
Field('sem_file', 'upload', label='Files', requires=False)
               
)
db
.seminars.sem_file.represent = lambda value,row:A('Download', _href=URL('download', args=value))

----------

def index():
    db
.seminars.id.readable=False
    grid
= SQLFORM.grid(db.seminars, maxtextlength=150,
                        details
=False, deletable=False, searchable=False, csv=False,  editargs=dict(id=False),  formstyle='bootstrap')
    grid
.element('.web2py_counter', replace=None)
   
return dict(grid=grid)

----------

{{extend 'seminar_layout.html'}}

{{=grid}}


It works fine as intended. But, I want to replace "Download" link with "No Files Available" and disable the link when there are there are no files available. Any suggestion or help is appreciated.

Thanks,
PT

Leonel Câmara

unread,
Feb 27, 2015, 12:56:58 PM2/27/15
to web...@googlegroups.com
Hey, 

How about this:

db.seminars.sem_file.represent = lambda value,row:A('Download', _href=URL('download', args=value)) if value else "No Files Available"


P T

unread,
Feb 27, 2015, 1:04:27 PM2/27/15
to web...@googlegroups.com
Thanks Leonel, it works great. But, I am stumped by the syntax.

Leonel Câmara

unread,
Feb 27, 2015, 1:32:03 PM2/27/15
to
The syntax is just regular python, what I've used is called a conditional expression which is python's version of the ternary operator.

It has the form:

a if test else b

Which is equivalent to this in many languages:

test ? a : b;


So what's happening here is that the value is None if there's no file, None evaluates to False when used as a boolean. So what the syntax actually means is - return the link if there's a value otherwise return "No Files Available", which coincidentally is exactly what you wanted.

P T

unread,
Feb 27, 2015, 3:01:50 PM2/27/15
to web...@googlegroups.com
Thank you Leonel for taking the time to explain the syntax!

Best Regards,
PT



On Friday, February 27, 2015 at 11:45:03 AM UTC-6, P T wrote:
Reply all
Reply to author
Forward
0 new messages