Skip to content

Instantly share code, notes, and snippets.

@rochacbruno
Created August 23, 2011 02:55
Show Gist options
  • Select an option

  • Save rochacbruno/1164226 to your computer and use it in GitHub Desktop.

Select an option

Save rochacbruno/1164226 to your computer and use it in GitHub Desktop.
Fix for web2py upload widget that was missing 'for' attr in label
class Upload(FormWidget):
DEFAULT_WIDTH = '150px'
ID_DELETE_SUFFIX = '__delete'
GENERIC_DESCRIPTION = 'file'
DELETE_FILE = 'delete'
@staticmethod
def widget(field, value, download_url=None, **attributes):
"""
generates a INPUT file tag.
Optionally provides an A link to the file, including a checkbox so
the file can be deleted.
All is wrapped in a DIV.
see also: :meth:`FormWidget.widget`
:param download_url: Optional URL to link to the file (default = None)
"""
default=dict(
_type='file',
)
attr = Upload._attributes(field, default, **attributes)
inp = INPUT(**attr)
if download_url and value:
if callable(download_url):
url = download_url(value)
else:
url = download_url + '/' + value
(br, image) = ('', '')
if Upload.is_image(value):
br = BR()
image = IMG(_src = url, _width = Upload.DEFAULT_WIDTH)
requires = attr["requires"]
if requires == [] or isinstance(requires, IS_EMPTY_OR):
inp = DIV(inp, BR(),
INPUT(_type='checkbox',
_name=field.name + Upload.ID_DELETE_SUFFIX,
_id=field.name + Upload.ID_DELETE_SUFFIX),
LABEL(Upload.DELETE_FILE,_for=field.name + Upload.ID_DELETE_SUFFIX),
br, image)
else:
inp = DIV(inp, '[',
A(Upload.GENERIC_DESCRIPTION, _href = url),
']', br, image)
return inp
@staticmethod
def represent(field, value, download_url=None):
"""
how to represent the file:
- with download url and if it is an image: <A href=...><IMG ...></A>
- otherwise with download url: <A href=...>file</A>
- otherwise: file
:param field: the field
:param value: the field value
:param download_url: url for the file download (default = None)
"""
inp = UploadWidget.GENERIC_DESCRIPTION
if download_url and value:
if callable(download_url):
url = download_url(value)
else:
url = download_url + '/' + value
if UploadWidget.is_image(value):
inp = IMG(_src = url, _width = UploadWidget.DEFAULT_WIDTH)
inp = A(inp, _href = url)
return inp
@staticmethod
def is_image(value):
"""
Tries to check if the filename provided references to an image
Checking is based on filename extension. Currently recognized:
gif, png, jp(e)g, bmp
:param value: filename
"""
extension = value.split('.')[-1].lower()
if extension in ['gif', 'png', 'jpg', 'jpeg', 'bmp']:
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment