desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Constructor
@param opts: the widget options
@keyword date_format: the date format (falls back to
deployment_settings.L10n.date_format)
@keyword time_format: the time format (falls back to
deployment_settings.L10n.time_format)
@keyword separator: the date/time separator (falls back to
deployment_settings.L10n.datetime_... | def __init__(self, **opts):
| self.opts = Storage(opts)
self._class = 'datetimepicker'
|
'Widget builder.
@param field: the Field
@param value: the current value
@param attributes: the HTML attributes for the widget'
| def __call__(self, field, value, **attributes):
| self.inject_script(field, value, **attributes)
default = dict(_type='text', _class=self._class, value=value)
attr = StringWidget._attributes(field, default, **attributes)
if ('_id' not in attr):
attr['_id'] = str(field).replace('.', '_')
widget = INPUT(**attr)
widget.add_class(self._clas... |
'Helper function to inject the document-ready-JavaScript for
this widget.
@param field: the Field
@param value: the current value
@param attributes: the HTML attributes for the widget'
| def inject_script(self, field, value, **attributes):
| ISO = '%Y-%m-%dT%H:%M:%S'
opts = self.opts
if ('_id' in attributes):
selector = attributes['_id']
else:
selector = str(field).replace('.', '_')
settings = current.deployment_settings
date_format = opts.get('date_format', settings.get_L10n_date_format())
time_format = opts.get... |
'Constructor
@param link: the name of the link table
@param component: the name of the component table
@param autocomplete: name of the autocomplete field
@param link_filter: filter expression to filter out records
in the component that are already linked
to the main record
@param select_existing: allow the selection o... | def __init__(self, link=None, component=None, autocomplete=None, link_filter=None, select_existing=True):
| self.link = link
self.component = component
self.autocomplete = autocomplete
self.select_existing = select_existing
self.link_filter = link_filter
|
'Widget renderer
@param field: the Field
@param value: the current value
@param attributes: the HTML attributes for the widget'
| def __call__(self, field, value, **attributes):
| T = current.T
if ('_id' in attributes):
input_id = attributes['_id']
else:
input_id = str(field).replace('.', '_')
s3 = current.response.s3
formstyle = s3.crud.formstyle
if ((not callable(formstyle)) or isinstance(formstyle('', '', '', ''), tuple)):
widgetstyle = self._fo... |
'Fallback for legacy formstyles (i.e. not callable or tuple-rows)'
| @staticmethod
def _formstyle(row_id, label, widget, comments):
| return TR(TD(label, widget, _class='w2p_fw'), TD(comments), _id=row_id)
|
'Parse a link filter expression and convert it into an
S3ResourceQuery that can be added to the search_ac resource.
Link filter expressions are used to exclude records from
the (autocomplete-)search that are already linked to the master
record.
General format:
?link=<linktablename>.<leftkey>.<id>.<rkey>.<fkey>
Example:... | @staticmethod
def link_filter(table, expression):
| try:
(link, lkey, _id, rkey, fkey) = expression.split('.')
except ValueError:
return None
linktable = current.s3db.table(link)
if linktable:
fq = ((linktable[rkey] == table[fkey]) & (linktable[lkey] == _id))
if ('deleted' in linktable):
fq &= (linktable.delete... |
'Constructor
@param options: the options for the SELECT, as list of tuples
[(value, label)], or as dict {value: label},
or None to auto-detect the options from the
Field when called
@param multiple: multiple options can be selected
@param size: maximum number of options in merged letter-groups,
None to not group option... | def __init__(self, options=None, multiple=True, size=None, cols=None, help_field=None, none=None, sort=True, orientation=None, table=True):
| self.options = options
self.multiple = multiple
self.size = size
self.cols = (cols or 3)
self.help_field = help_field
self.none = none
self.sort = sort
self.orientation = orientation
self.table = table
|
'Render this widget
@param field: the Field
@param value: the currently selected value(s)
@param attributes: HTML attributes for the widget'
| def __call__(self, field, value, **attributes):
| fieldname = field.name
attr = Storage(attributes)
if ('_id' in attr):
_id = attr.pop('_id')
else:
_id = ('%s-options' % fieldname)
attr['_id'] = _id
if ('_name' not in attr):
attr['_name'] = fieldname
options = self._options(field, value)
if self.multiple:
... |
'Helper method to render an options group
@param group: the group as dict {label:label, items:[items]}'
| def _render_group(self, group):
| items = group['items']
if items:
label = group['label']
render_item = self._render_item
options = [render_item(i) for i in items]
if label:
return [OPTGROUP(options, _label=label)]
else:
return options
else:
return None
|
'Helper method to render one option
@param item: the item as tuple (key, label, value, tooltip),
value=True indicates that the item is selected'
| @staticmethod
def _render_item(item):
| (key, label, value, tooltip) = item
attr = {'_value': key}
if value:
attr['_selected'] = 'selected'
if tooltip:
attr['_title'] = tooltip
return OPTION(label, **attr)
|
'Find, group and sort the options
@param field: the Field
@param value: the currently selected value(s)'
| def _options(self, field, value):
| options = self.options
if (options is None):
requires = field.requires
if (not isinstance(requires, (list, tuple))):
requires = [requires]
if hasattr(requires[0], 'options'):
options = requires[0].options()
else:
options = []
elif isinstanc... |
'Helper method to finalize an options group, render its label
and sort the options
@param group: the group as dict {letters: [], items: []}
@param values: the currently selected values as list
@param helptext: dict of {key: helptext} for the options'
| @staticmethod
def _close_group(group, values, helptext, sort=True):
| group_letters = group['letters']
if group_letters:
if (len(group_letters) > 1):
group['label'] = ('%s - %s' % (group_letters[0], group_letters[(-1)]))
else:
group['label'] = group_letters[0]
else:
group['label'] = None
del group['letters']
if sor... |
'Constructor
@param options: the options for the SELECT, as list of tuples
[(value, label)], or as dict {value: label},
or None to auto-detect the options from the
Field when called
@param cols: number of columns for the options table
@param help_field: field in the referenced table to retrieve
a tooltip text from (for... | def __init__(self, options=None, cols=None, help_field=None, none=None, sort=True):
| self.options = options
self.cols = (cols or 3)
self.help_field = help_field
self.none = none
self.sort = sort
|
'Render this widget
@param field: the Field
@param value: the currently selected value(s)
@param attributes: HTML attributes for the widget'
| def __call__(self, field, value, **attributes):
| fieldname = field.name
attr = Storage(attributes)
if ('_id' in attr):
_id = attr.pop('_id')
else:
_id = ('%s-options' % fieldname)
attr['_id'] = _id
if ('_name' not in attr):
attr['_name'] = fieldname
options = self._options(field, value)
if ('empty' in options):
... |
'Helper method to render one option
@param item: the item as tuple (key, label, value, tooltip),
value=True indicates that the item is selected'
| @staticmethod
def _render_item(fieldname, item):
| (key, label, value, tooltip) = item
id = ('%s%s' % (fieldname, key))
attr = {'_type': 'radio', '_name': fieldname, '_id': id, '_class': 's3-radioopts-option', '_value': key}
if value:
attr['_checked'] = 'checked'
if tooltip:
attr['_title'] = tooltip
return DIV(INPUT(**attr), LABE... |
'Find and sort the options
@param field: the Field
@param value: the currently selected value(s)'
| def _options(self, field, value):
| options = self.options
if (options is None):
requires = field.requires
if (not isinstance(requires, (list, tuple))):
requires = [requires]
if hasattr(requires[0], 'options'):
options = requires[0].options()
else:
options = []
elif isinstanc... |
'@param image_bounds: Limits the Size of the Image that can be
uploaded.
Tuple/List - (MaxWidth, MaxHeight)'
| def __init__(self, image_bounds=None):
| self.image_bounds = image_bounds
|
'@param field: Field using this widget
@param value: value if any
@param download_url: Download URL for saved Image'
| def __call__(self, field, value, download_url=None, **attributes):
| T = current.T
script_dir = ('/%s/static/scripts' % current.request.application)
s3 = current.response.s3
debug = s3.debug
scripts = s3.scripts
settings = current.deployment_settings
if debug:
script = ('%s/jquery.color.js' % script_dir)
if (script not in scripts):
... |
'Returns a widget with key-value fields'
| def __init__(self, key_label=None, value_label=None):
| self._class = 'key-value-pairs'
T = current.T
self.key_label = (key_label or T('Key'))
self.value_label = (value_label or T('Value'))
|
'Set Defaults'
| def __init__(self, level='L0', default=None, empty=False):
| self.level = level
self.default = default
self.empty = empty
|
'Set Defaults'
| def __init__(self, empty=False):
| self.empty = empty
|
'Widget renderer.
To be implemented in subclass.
@param field: the Field
@param value: the current value(s)
@param attr: additional HTML attributes for the widget
@return: the widget HTML'
| def __call__(self, field, value, **attributes):
| values = self.parse(value)
return self.inputfield(field, values, 's3-selector', **attributes)
|
'Extract the record from the database and update values.
To be implemented in subclass.
@param record_id: the record ID
@param values: the values dict
@return: the (updated) values dict'
| def extract(self, record_id, values=None):
| if (values is None):
values = {}
values['id'] = record_id
return values
|
'Representation method for new or updated value dicts.
IMPORTANT: This method *must not* change DB status because it
is called from inline forms before the the row is
committed to the DB, so any DB status change would
be invalid at this point.
To be implemented in subclass.
@param values: the values dict
@return: strin... | def represent(self, value):
| return s3_unicode(value)
|
'Parse and validate the input value, but don\'t create or update
any records. This will be called by S3CRUD.validate to validate
inline-form values.
To be implemented in subclass.
@param value: the value from the form
@returns: tuple (values, error) with values being the parsed
value dict, and error any validation erro... | def validate(self, value):
| values = self.parse(value)
return (values, None)
|
'Post-process to create or update records. Called during POST
before validation of the outer form.
To be implemented in subclass.
@param value: the value from the form (as JSON)
@return: tuple (record_id, error)'
| def postprocess(self, value):
| (values, error) = self.validate(value)
if values:
record_id = values.get('id')
else:
record_id = None
if error:
return (None, error)
return (record_id, None)
|
'Generate the (hidden) input field. Should be used in __call__.
@param field: the Field
@param values: the parsed value (as dict)
@param classes: standard HTML classes
@param attributes: the widget attributes as passed in to the widget
@return: the INPUT field'
| def inputfield(self, field, values, classes, **attributes):
| if isinstance(classes, (tuple, list)):
_class = ' '.join(classes)
else:
_class = classes
requires = self.postprocess
fieldname = str(field).replace('.', '_')
if fieldname.startswith('sub_'):
from s3forms import SKIP_POST_VALIDATION
requires = SKIP_POST_VALIDATION(r... |
'Serialize the values (as JSON string). Called from inputfield().
@param values: the values (as dict)
@return: the serialized values'
| def serialize(self, values):
| return json.dumps(values, separators=SEPARATORS)
|
'Parse the form value into a dict. The value would be a record
id if coming from the database, or a JSON string when coming
from a form. Should be called from validate(), doesn\'t need to
be re-implemented in subclass.
@param value: the value
@return: the parsed data as dict'
| def parse(self, value):
| record_id = None
values = None
if value:
if isinstance(value, basestring):
if value.isdigit():
record_id = long(value)
else:
try:
values = json.loads(value)
except ValueError:
pass
... |
'Constructor
@param levels: list or tuple of hierarchy levels (names) to expose,
in order (e.g. ("L0", "L1", "L2"))
@param required_levels: list or tuple of required hierarchy levels (if empty,
only the highest selectable Lx will be required)
@param hide_lx: hide Lx selectors until higher level has been selected
@param... | def __init__(self, levels=None, required_levels=None, hide_lx=True, reverse_lx=False, show_address=False, show_postcode=None, show_latlon=None, latlon_mode='decimal', latlon_mode_toggle=True, show_map=None, open_map_on_load=False, feature_required=False, lines=False, points=True, polygons=False, circles=False, color_pi... | settings = current.deployment_settings
self._initlx = True
self._levels = levels
self._required_levels = required_levels
self._load_levels = None
self.hide_lx = hide_lx
self.reverse_lx = reverse_lx
self.show_address = show_address
self.show_postcode = show_postcode
self.prevent_d... |
'Lx-levels to expose as dropdowns'
| @property
def levels(self):
| levels = self._levels
if self._initlx:
lx = []
if (not levels):
levels = current.gis.get_relevant_hierarchy_levels()
if (levels is None):
levels = []
if (not isinstance(levels, (tuple, list))):
levels = [levels]
for level in levels:
... |
'Lx-levels to treat as required'
| @property
def required_levels(self):
| levels = self._required_levels
if self._initlx:
if (levels is None):
levels = set()
elif (not isinstance(levels, (list, tuple))):
levels = [levels]
self._required_levels = levels
return levels
|
'Lx-levels to load from the database = all levels down to the
lowest exposed level (L0=highest, L5=lowest)'
| @property
def load_levels(self):
| load_levels = self._load_levels
if (load_levels is None):
load_levels = ('L0', 'L1', 'L2', 'L3', 'L4', 'L5')
while load_levels:
if (load_levels[(-1)] in self.levels):
break
else:
load_levels = load_levels[:(-1)]
self._load_levels = ... |
'Widget renderer
@param field: the Field
@param value: the current value(s)
@param attr: additional HTML attributes for the widget'
| def __call__(self, field, value, **attributes):
| T = current.T
db = current.db
s3db = current.s3db
request = current.request
s3 = current.response.s3
requires = field.requires
if requires:
required = (not hasattr(requires, 'other'))
else:
required = False
if (request.controller == 'appadmin'):
attr = FormWid... |
'Extract the hierarchy labels
@param levels: the exposed hierarchy levels
@param country: the country (gis_location record ID) for which
to read the hierarchy labels
@return: tuple (labels, compact) where labels is for
internal use with _lx_selectors, and compact
the version ready for JSON output
@ToDo: Country-specifi... | def _labels(self, levels, country=None):
| T = current.T
table = current.s3db.gis_hierarchy
fields = [table[level] for level in levels if (level != 'L0')]
query = (table.uuid == 'SITE_DEFAULT')
if country:
fields.append(table.uuid)
query |= (table.location_id == country)
limit = 2
else:
limit = 1
rows ... |
'Build initial location dict (to populate Lx dropdowns)
@param levels: the exposed levels
@param values: the current values
@param default_bounds: the default bounds (if already known, e.g.
single-country deployment)
@param lowest_lx: the lowest un-selectable Lx level (to determine
default bounds if not passed in)
@par... | def _locations(self, levels, values, default_bounds=None, lowest_lx=None, config=None):
| db = current.db
s3db = current.s3db
settings = current.deployment_settings
L0 = values.get('L0')
L1 = values.get('L1')
L2 = values.get('L2')
L3 = values.get('L3')
L4 = values.get('L4')
gtable = s3db.gis_location
if ('L0' in levels):
query = (gtable.level == 'L0')
... |
'Overall layout for visible components
@param components: the components as dict
{name: (label, widget, id, hidden)}
@param map icon: the map icon
@param formstyle: the formstyle (falls back to CRUD formstyle)'
| def _layout(self, components, map_icon=None, formstyle=None, inline=False):
| if (formstyle is None):
formstyle = current.response.s3.crud.formstyle
row = formstyle('test', 'test', 'test', 'test')
if isinstance(row, tuple):
tuple_rows = True
table_style = (inline and (row[0].tag == 'tr'))
else:
tuple_rows = False
table_style = False
sel... |
'Render the Lx-dropdowns
@param fieldname: the fieldname (to construct the HTML IDs)
@param levels: tuple of levels in order, like ("L0", "L1", ...)
@param labels: the labels for the hierarchy levels as dict {level:label}
@param required: whether selection is required,
@param multiselect: Use multiselect-dropdowns (spe... | def _lx_selectors(self, fieldname, levels, labels, required=False, multiselect=False):
| if (multiselect == 'search'):
_class = 'lx-select multiselect search'
elif multiselect:
_class = 'lx-select multiselect'
else:
_class = None
selectors = {}
hidden = True
required_levels = self.required_levels
for level in levels:
_id = ('%s_%s' % (fie... |
'Render a text input (e.g. address or postcode field)
@param fieldname: the field name (for ID construction)
@param name: the name for the input field
@param value: the initial value for the input
@param label: the label for the input
@param hidden: render hidden
@return: a tuple (label, widget, id, hidden)'
| def _input(self, fieldname, name, value, label, hidden=False, _class='string'):
| input_id = ('%s_%s' % (fieldname, name))
if self.labels:
_label = LABEL(('%s:' % label), _for=input_id)
else:
_label = ''
if self.placeholders:
_placeholder = label
else:
_placeholder = None
if isinstance(value, unicode):
value = value.encode('utf-8')
... |
'Initialize the map
@param field: the field
@param fieldname: the field name (to construct HTML IDs)
@param lat: the Latitude of the current point location
@param lon: the Longitude of the current point location
@param wkt: the WKT
@param radius: the radius of the location
@param callback: the script to initialize the ... | def _map(self, field, fieldname, lat, lon, wkt, radius, callback=None, geocoder=False, tablename=None):
| lines = self.lines
points = self.points
polygons = self.polygons
circles = self.circles
add_points_active = add_polygon_active = add_line_active = add_circle_active = False
if (points and lines):
toolbar = True
if wkt:
if ((not polygons) or wkt.startswith('LINE')):
... |
'Load record data from database and update the values dict
@param record_id: the location record ID
@param values: the values dict'
| def extract(self, record_id, values=None):
| if (values is None):
values = {}
for key in ('L0', 'L1', 'L2', 'L3', 'L4', 'L5', 'specific', 'parent', 'radius'):
if (key not in values):
values[key] = None
values['id'] = record_id
if (not record_id):
return values
db = current.db
table = current.s3db.gis_loc... |
'Representation of a new/updated location row (before DB commit).
NB: Using a fake path here in order to prevent
gis_LocationRepresent.represent_row() from running
update_location_tree as that would change DB status which
is an invalid action at this point (row not committed yet).
This method is called during S3CRUD.va... | def represent(self, value):
| if ((not value) or (not any((value.get(key) for key in self.keys)))):
return current.messages['NONE']
lat = value.get('lat')
lon = value.get('lon')
wkt = value.get('wkt')
radius = value.get('radius')
address = value.get('address')
postcode = value.get('postcode')
record = Storage... |
'Parse and validate the input value, but don\'t create or update
any location data
@param value: the value from the form
@param requires: the field validator
@returns: tuple (values, error) with values being the parsed
value dict, and error any validation errors'
| def validate(self, value, requires=None):
| values = self.parse(value)
if ((not values) or (not any((values.get(key) for key in self.keys)))):
if (requires and (not isinstance(requires, IS_EMPTY_OR))):
return (values, current.T('Location data required'))
return (values, None)
table = current.s3db.gis_location
err... |
'Takes the JSON from the real input and returns a location ID
for it. Creates or updates the location if necessary.
@param value: the JSON from the real input
@return: tuple (location_id, error)
@ToDo: Audit'
| def postprocess(self, value):
| (values, error) = self.validate(value)
if values:
location_id = values.get('id')
else:
location_id = None
if error:
return (None, error)
if (location_id is None):
return (location_id, None)
db = current.db
table = current.s3db.gis_location
lat = values.get... |
'Constructor
@param filter: show an input field in the widget to filter for options,
can be:
- True (always show filter field)
- False (never show the filter field)
- "auto" (show filter if more than 10 options)
- <number> (show filter if more than <number> options)
@param header: show a header for the options list, ca... | def __init__(self, filter='auto', header=True, multiple=True, selectedList=3, noneSelectedText='Select', columns=None, create=None):
| self.filter = filter
self.header = header
self.multiple = multiple
self.selectedList = selectedList
self.noneSelectedText = noneSelectedText
self.columns = columns
self.create = create
|
'Constructor
@param icons: show icons next to options,
can be:
- False (don\'t show icons)
- function (function to call add Icon URLs, height and width to the options)'
| def __init__(self, icons=False):
| self.icons = icons
|
'Generates a SELECT tag, including OPTIONs (only 1 option allowed)
see also: `FormWidget.widget`'
| def widget(self, field, value, **attributes):
| default = dict(value=value)
attr = self._attributes(field, default, **attributes)
requires = field.requires
if (not isinstance(requires, (list, tuple))):
requires = [requires]
if requires:
if hasattr(requires[0], 'options'):
options = requires[0].options()
else:
... |
'Constructor
@param lookup: name of the lookup table (must have a hierarchy
configured)
@param represent: alternative representation method (falls back
to the field\'s represent-method)
@param multiple: allow selection of multiple options
@param leafonly: True = only leaf nodes can be selected (with
multiple=True: sele... | def __init__(self, lookup=None, represent=None, multiple=True, leafonly=True, cascade=False, bulk_select=False, filter=None, columns=None, none=None):
| self.lookup = lookup
self.represent = represent
self.filter = filter
self.multiple = multiple
self.leafonly = leafonly
self.cascade = cascade
self.columns = columns
self.bulk_select = bulk_select
self.none = none
|
'Widget renderer
@param field: the Field
@param value: the current value(s)
@param attr: additional HTML attributes for the widget'
| def __call__(self, field, value, **attr):
| if isinstance(field, Field):
selector = str(field).replace('.', '_')
else:
selector = field.name.replace('.', '_')
widget_id = attr.get('_id')
if (widget_id == None):
widget_id = attr['_id'] = ('%s-hierarchy' % selector)
name = attr.get('_name')
if (not name):
nam... |
'Value parser for the hidden input field of the widget
@param value: the value received from the client, JSON string
@return: a list (if multiple=True) or the value'
| def parse(self, value):
| default = ([] if self.multiple else None)
if (value is None):
return (None, None)
try:
value = json.loads(value)
except ValueError:
return (default, None)
if ((not self.multiple) and isinstance(value, list)):
value = (value[0] if value else None)
return (value, No... |
'@type rows: tuple
@param rows:
A tuple of tuples.
The nested tuples will have the row label followed by a value
for each checkbox in that row.
@type cols: tuple
@param cols:
A tuple containing the labels to use in the column headers'
| def __init__(self, rows, cols):
| self.rows = rows
self.cols = cols
|
'Returns the grid/matrix of checkboxes as a web2py TABLE object and
adds references to required Javascript files.
@type field: Field
@param field:
This gets passed in when the widget is rendered or used.
@type value: list
@param value:
A list of the values matching those of the checkboxes.
@param attributes:
HTML attri... | def __call__(self, field, value, **attributes):
| if isinstance(value, (list, tuple)):
values = [str(v) for v in value]
else:
values = [str(value)]
header_cells = []
for col in self.cols:
header_cells.append(TH(col, _scope='col'))
header = THEAD(TR(header_cells))
grid_rows = []
for row in self.rows:
row_cells... |
'[{"id":12, "pe_id":4, "name":"Organisation Name"}]'
| def __init__(self, primary_options=None):
| self.primary_options = primary_options
|
'Constructor
@param columns: number of grid columns to span (Foundation-themes)
@param placeholder: placeholder text for the input field
@param prefix: text for prefix button (Foundation-themes)
@param textarea: render as textarea rather than string input'
| def __init__(self, columns=10, placeholder=None, prefix=None, textarea=False):
| self.columns = columns
self.placeholder = placeholder
self.prefix = prefix
self.textarea = textarea
|
'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: :meth:`FormWidget.widget`
@param download_url: Optional URL to link to the file (default = None)'
| @classmethod
def widget(cls, field, value, download_url=None, **attributes):
| T = current.T
default = {'_type': 'file'}
attr = cls._attributes(field, default, **attributes)
base_url = '/default/download'
if (download_url and value):
if callable(download_url):
url = download_url(value)
else:
base_url = download_url
url = ((do... |
'Constructor
@param options: the options for the widget, either as iterable of
tuples (value, representation) or as dict
{value:representation}, or as iterable of strings
if value is the same as representation
@param translate: automatically translate the representation
@param sort: alpha-sort options (by representatio... | def __init__(self, options, translate=False, sort=True, empty=True):
| self.options = options
self.translate = translate
self.sort = sort
self.empty = empty
|
'generates a TABLE tag, including INPUT checkboxes (multiple allowed)
see also: :meth:`FormWidget.widget`'
| @classmethod
def widget(cls, field, value, **attributes):
| values = (((not isinstance(value, (list, tuple))) and [value]) or value)
values = [str(v) for v in values]
attr = OptionsWidget._attributes(field, {}, **attributes)
attr['_class'] = 'checkboxes-widget-s3'
requires = field.requires
if (not isinstance(requires, (list, tuple))):
requires = ... |
'Constructor
@param contents: the contents (string)'
| def __init__(self, contents):
| self.contents = contents
|
'Replace {{}} expressions with local URLs, with the ability to
override controller, function and URL query variables.Called
from re.sub.
@param match: the re match object'
| def link(self, match):
| tokens = match.group(1).split(',')
args = True
parameters = {}
arguments = []
collect_args = False
for token in tokens:
if (not token):
continue
elif (':' in token):
collect_args = False
(key, value) = token.split(':')
else:
... |
'Render the output'
| def xml(self):
| return re.sub('\\{\\{(.+?)\\}\\}', self.link, self.contents)
|
'Widget builder
@param field: the Field
@param value: the current value
@param attributes: the HTML attributes for the widget'
| def __call__(self, field, value, **attr):
| selector = attr.get('id')
if (not selector):
if isinstance(field, Field):
selector = str(field).replace('.', '_')
else:
selector = field.name.replace('.', '_')
name = attr.get('_name')
if (not name):
name = field.name
T = current.T
request = curren... |
'Overall layout for visible components
@param components: the components as dict
@param formstyle: the formstyle (falls back to CRUD formstyle)'
| def _layout(self, components, formstyle=None):
| if (formstyle is None):
formstyle = current.response.s3.crud.formstyle
row = formstyle('test', 'test', 'test', 'test')
tuple_rows = isinstance(row, tuple)
inputs = TAG['']()
for name in ('type', 'is_required', 'description', 'default_answer', 'max', 'min', 'filter', 'reference', 'represent',... |
'Render a text input with given attributes
@param fieldname: the field name (for ID construction)
@param name: the name for the input field
@param value: the initial value for the input
@param label: the label for the input
@param hidden: render hidden
@return: a tuple (label, widget, id, hidden)'
| def _input(self, fieldname, name, value, label, _type='text'):
| input_id = ('%s_%s' % (fieldname, name))
_label = LABEL(('%s: ' % label), _for=input_id)
if isinstance(value, unicode):
value = value.encode('utf-8')
if (name in ('is_required', 'multiple')):
widget = INPUT(_type=_type, _id=input_id, value=value)
else:
widget = INPUT(_type... |
'Constructor
@param name: the abstract icon name
@param attr: additional HTML attributes (optional)'
| def __init__(self, name, **attr):
| self.name = name
super(ICON, self).__init__(' ', **attr)
|
'Render this instance as XML'
| def xml(self):
| layout = current.deployment_settings.get_ui_icon_layout()
if layout:
return layout(self)
css_class = self.css_class(self.name)
if css_class:
self.add_class(css_class)
return super(ICON, self).xml()
|
'Initialise parent class & make any necessary modifications'
| def __init__(self):
| Auth.__init__(self, current.db)
self.settings.lock_keys = False
self.settings.login_userfield = 'email'
self.settings.lock_keys = True
messages = self.messages
messages.lock_keys = False
messages.approve_user = 'Your action is required to approve a New User for ... |
'to be called unless tables are defined manually
usages::
# defines all needed tables and table files
# UUID + "_auth_user.table", ...
auth.define_tables()
# defines all needed tables and table files
# "myprefix_auth_user.table", ...
auth.define_tables(migrate="myprefix_")
# defines all needed tables without migration/... | def define_tables(self, migrate=True, fake_migrate=False):
| db = current.db
settings = self.settings
messages = self.messages
deployment_settings = current.deployment_settings
define_table = db.define_table
utable = settings.table_user
uname = settings.table_user_name
if (not utable):
utable_fields = [Field('first_name', length=128, notnu... |
'Logs user in
- extended to understand session.s3.roles'
| def login_bare(self, username, password):
| settings = self.settings
utable = settings.table_user
userfield = settings.login_userfield
passfield = settings.password_field
query = (utable[userfield] == username)
user = current.db(query).select(limitby=(0, 1)).first()
password = utable[passfield].validate(password)[0]
if user:
... |
'Set a Cookie to the client browser so that we know this user has
registered & so we should present them with a login form instead
of a register form'
| def set_cookie(self):
| cookies = current.response.cookies
cookies['registered'] = 'yes'
cookies['registered']['expires'] = ((365 * 24) * 3600)
cookies['registered']['path'] = '/'
|
'Overrides Web2Py\'s login() to use custom flash styles & utcnow
@return: a login form'
| def login(self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, inline=False, lost_pw_link=None, register_link=True):
| T = current.T
db = current.db
messages = self.messages
request = current.request
response = current.response
session = current.session
settings = self.settings
deployment_settings = current.deployment_settings
utable = settings.table_user
userfield = settings.login_userfield
... |
'Returns a form that lets the user change password'
| def change_password(self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT):
| if (not self.is_logged_in()):
redirect(self.settings.login_url, client_side=self.settings.client_side)
messages = self.messages
settings = self.settings
utable = settings.table_user
s = self.db((utable.id == self.user.id))
request = current.request
session = current.session
if (n... |
'Returns a form to reset the user password, overrides web2py\'s
version of the method to apply Eden formstyles.
@param next: URL to redirect to after successful form submission
@param onvalidation: callback to validate password reset form
@param onaccept: callback to post-process password reset request
@param log: even... | def request_reset_password(self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT):
| messages = self.messages
settings = self.settings
utable = settings.table_user
request = current.request
response = current.response
session = current.session
captcha = (settings.retrieve_password_captcha or ((settings.retrieve_password_captcha != False) and settings.captcha))
if (next i... |
'Log the user in
- common function called by login() & register()'
| def login_user(self, user):
| db = current.db
deployment_settings = current.deployment_settings
request = current.request
session = current.session
settings = self.settings
req_vars = request.vars
if (not user.utc_offset):
user.utc_offset = session.s3.utc_offset
session.auth = Storage(user=user, last_visit=re... |
'Overrides Web2Py\'s register() to add new functionality:
- Checks whether registration is permitted
- Custom Flash styles
- Allow form to be embedded in other pages
- Optional addition of Mobile Phone field to the Register form
- Optional addition of Organisation field to the Register form
- Lookup Domains/Organisatio... | def register(self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, js_validation=True):
| db = current.db
settings = self.settings
messages = self.messages
request = current.request
session = current.session
deployment_settings = current.deployment_settings
T = current.T
customise = deployment_settings.customise_resource('auth_user')
if customise:
customise(reques... |
'Overrides Web2Py\'s email_reset_password() to modify the message
structure
@param user: the auth_user record (Row)'
| def email_reset_password(self, user):
| mailer = self.settings.mailer
if (not mailer):
return False
import time
reset_password_key = ((str(int(time.time())) + '-') + web2py_uuid())
reset_password_url = ('%s/default/user/reset_password?key=%s' % (current.response.s3.base_url, reset_password_key))
message = (self.messages.reset_... |
'gives user_id membership of group_id or role
if user is None than user_id is that of current logged in user
S3: extended to support Entities'
| def add_membership(self, group_id=None, user_id=None, role=None, entity=None):
| group_id = (group_id or self.id_group(role))
try:
group_id = int(group_id)
except:
group_id = self.id_group(group_id)
if ((not user_id) and self.user):
user_id = self.user.id
membership = self.settings.table_membership
record = membership(user_id=user_id, group_id=group_i... |
'action user to verify the registration email, XXXXXXXXXXXXXXXX
.. method:: Auth.verify_email([next=DEFAULT [, onvalidation=DEFAULT
[, log=DEFAULT]]])'
| def verify_email(self, next=DEFAULT, log=DEFAULT):
| settings = self.settings
request = current.request
customise = current.deployment_settings.customise_resource('auth_user')
if customise:
customise(request, 'auth_user')
key = request.args[(-1)]
utable = settings.table_user
query = (utable.registration_key == key)
user = current.d... |
'returns a form that lets the user change his/her profile
.. method:: Auth.profile([next=DEFAULT [, onvalidation=DEFAULT
[, onaccept=DEFAULT [, log=DEFAULT]]]])
Patched for S3 to use s3_mark_required and handle opt_in mailing lists'
| def profile(self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT):
| if (not self.is_logged_in()):
redirect(self.settings.login_url)
messages = self.messages
settings = self.settings
utable = settings.table_user
passfield = settings.password_field
utable[passfield].writable = False
request = current.request
session = current.session
deployment... |
'Configure User Fields - for registration & user administration
pe_ids: an optional list of pe_ids for the Org Filter
i.e. org_admin coming from admin.py/user()'
| def configure_user_fields(self, pe_ids=None):
| from s3validators import IS_ONE_OF
T = current.T
db = current.db
s3db = current.s3db
request = current.request
messages = self.messages
cmessages = current.messages
settings = self.settings
deployment_settings = current.deployment_settings
if deployment_settings.get_ui_multiselec... |
'Called when users are imported from CSV
Lookups Pseudo-reference Integer fields from Names
e.g.:
auth_membership.pe_id from organisation.name=<Org Name>'
| def s3_import_prep(self, data):
| db = current.db
s3db = current.s3db
set_record_owner = self.s3_set_record_owner
update_super = s3db.update_super
otable = s3db.org_organisation
btable = s3db.org_organisation_branch
(resource, tree) = data
ORG_ADMIN = (not self.s3_has_role('ADMIN'))
TRANSLATE = current.deployment_set... |
'JavaScript client-side validation for Registration / User profile
- needed to check for passwords being same, etc'
| @staticmethod
def s3_register_validation():
| T = current.T
request = current.request
appname = request.application
settings = current.deployment_settings
s3 = current.response.s3
scripts_append = s3.scripts.append
if s3.debug:
scripts_append(('/%s/static/scripts/jquery.validate.js' % appname))
scripts_append(('/%s/stati... |
'S3 framework function
Designed to be called when a user is created through:
- registration via OAuth, LDAP, etc
Does the following:
- Sets session.auth.user for authorstamp, etc
- Approves user (to set registration groups, such as AUTHENTICATED, link to Person)'
| def s3_register_onaccept(self, form):
| user = form.vars
current.session.auth = Storage(user=user)
self.s3_approve_user(user)
|
'S3 framework function
Designed to be called when a user is created through:
- registration
Does the following:
- Stores the user\'s email & profile image in auth_user_temp
to be added to their person record when created on approval
@ToDo: If these fields are implemented with the InlineForms functionality,
this functio... | def s3_user_register_onaccept(self, form):
| db = current.db
s3db = current.s3db
session = current.session
utable = self.settings.table_user
temptable = s3db.auth_user_temp
form_vars = form.vars
user_id = form_vars.id
if (not user_id):
return None
if (not form_vars.utc_offset):
db((utable.id == user_id)).update(... |
'Designed to be called when a user is verified through:
- responding to their verification email
- if verification isn\'t required
Does the following:
- Sends a message to the approver to notify them if a user needs approval
- If deployment_settings.auth.always_notify_approver = True,
send them notification regardless
... | def s3_verify_user(self, user):
| db = current.db
deployment_settings = current.deployment_settings
session = current.session
utable = self.settings.table_user
(approver, organisation_id) = self.s3_approver(user)
if (deployment_settings.get_auth_registration_requires_approval() and approver):
approved = False
db(... |
'S3 framework function
Designed to be called when a user is created through:
- prepop
- approved automatically during registration
- approved by admin
- added by admin
- updated by admin
Does the following:
- Adds user to the \'Authenticated\' role
- Adds any default roles for the user
- @ToDo: adds them to the Org_x A... | def s3_approve_user(self, user, password=None):
| user_id = user.id
if (not user_id):
return None
db = current.db
s3db = current.s3db
deployment_settings = current.deployment_settings
settings = self.settings
utable = settings.table_user
authenticated = self.id_group('Authenticated')
add_membership = self.add_membership
... |
'S3 framework function
Designed to be called when a user is created & approved through:
- prepop
- approved automatically during registration
- approved by admin
- added by admin
- updated by admin
Does the following:
- Calls s3_link_to_organisation:
Creates (if not existing) User\'s Organisation and links User
- Calls... | def s3_link_user(self, user):
| organisation_id = self.s3_link_to_organisation(user)
person_id = self.s3_link_to_person(user, organisation_id)
if user.org_group_id:
self.s3_link_to_org_group(user, person_id)
utable = self.settings.table_user
link_user_to = (user.link_user_to or utable.link_user_to.default)
if link_user... |
'Update the UI locale from user profile'
| @staticmethod
def s3_user_profile_onaccept(form):
| if form.vars.language:
current.session.s3.language = form.vars.language
|
'Links user accounts to person registry entries
@param user: the user record
@param organisation_id: the user\'s organisation_id
to get the person\'s realm_entity
Policy for linking to pre-existing person records:
If this user is already linked to a person record with a different
first_name, last_name, email or realm_e... | def s3_link_to_person(self, user=None, organisation_id=None):
| db = current.db
s3db = current.s3db
utable = self.settings.table_user
ttable = s3db.auth_user_temp
ptable = s3db.pr_person
ctable = s3db.pr_contact
atable = s3db.pr_address
gctable = s3db.gis_config
ltable = s3db.pr_person_user
if organisation_id:
org_pe_id = s3db.pr_get_... |
'Link a user account to an organisation
@param user: the user account record'
| def s3_link_to_organisation(self, user):
| db = current.db
s3db = current.s3db
user_id = user.id
(approver, organisation_id) = self.s3_approver(user)
if organisation_id:
user.organisation_id = organisation_id
else:
organisation_id = user.organisation_id
if (not organisation_id):
name = user.get('organisation_n... |
'Link a user account to an organisation group
@param user: the user account record
@param person_id: the person record ID associated with this user'
| def s3_link_to_org_group(self, user, person_id):
| db = current.db
s3db = current.s3db
org_group_id = user.get('org_group_id')
if ((not org_group_id) or (not person_id)):
return None
stable = s3db.org_group_person_status
query = ((stable.name.lower() == 'member') & (stable.deleted != True))
row = db(query).select(stable.id, limitby=(... |
'Take ownership of the HR records of the person record
@ToDo: Add user to the Org Access role.'
| def s3_link_to_human_resource(self, user, person_id, hr_type):
| db = current.db
s3db = current.s3db
settings = current.deployment_settings
user_id = user.id
organisation_id = user.organisation_id
htablename = 'hrm_human_resource'
htable = s3db.table(htablename)
if ((not htable) or ((not organisation_id) and settings.get_hrm_org_required())):
... |
'Link to a member Record'
| def s3_link_to_member(self, user, person_id=None):
| db = current.db
s3db = current.s3db
user_id = user.id
organisation_id = user.organisation_id
mtablename = 'member_membership'
mtable = s3db.table(mtablename)
if ((not mtable) or (not organisation_id)):
return None
ptable = s3db.pr_person
ltable = s3db.pr_person_user
query... |
'Returns the Approver for a new Registration &
the organisation_id field
@param: user - the user record (form.vars when done direct)
@ToDo: Support multiple approvers per Org - via Org Admin (or specific Role?)
Split into separate functions to returning approver & finding users\' org from auth_organisations
@returns ap... | def s3_approver(self, user):
| db = current.db
approver = None
organisation_id = user.get('organisation_id')
table = current.s3db.auth_organisation
if organisation_id:
query = ((table.organisation_id == organisation_id) & (table.deleted == False))
record = db(query).select(table.approver, limitby=(0, 1)).first()
... |
'Send a welcome mail to newly-registered users
- especially suitable for users from Facebook/Google who don\'t
verify their emails
@param user: the user dict, must contain "email", and can
contain "language" for translation of the message
@param password: optional password to include in a custom welcome_email'
| def s3_send_welcome_email(self, user, password=None):
| messages = self.messages
settings = current.deployment_settings
if (not settings.get_mail_sender()):
current.response.error = messages.unable_send_email
return
T = current.T
language = user.get('language')
if language:
T.force(language)
system_name = s3_str(settings.g... |
'S3 framework function
Designed to be used within tasks, which are run in a separate
request & hence don\'t have access to current.auth
@param user_id: auth.user.id or auth.user.email'
| def s3_impersonate(self, user_id):
| settings = self.settings
utable = settings.table_user
query = None
if (not user_id):
user = None
elif (isinstance(user_id, basestring) and (not user_id.isdigit())):
query = (utable[settings.login_userfield] == user_id)
else:
query = (utable.id == user_id)
if (query is... |
'Check whether the user is currently logged-in
- tries Basic if not'
| def s3_logged_in(self):
| if self.override:
return True
if (not self.is_logged_in()):
basic = self.basic()
try:
return basic[2]
except TypeError:
return basic
except:
return False
return True
|
'Get the IDs of the session roles by their UIDs, and store them
in the current session, as these IDs should never change.'
| def get_system_roles(self):
| s3 = current.session.s3
try:
system_roles = s3.system_roles
except:
s3 = Storage()
else:
if system_roles:
return system_roles
gtable = self.settings.table_group
if (gtable is not None):
S3_SYSTEM_ROLES = self.S3_SYSTEM_ROLES
query = ((gtable.de... |
'Update pe_id, roles and realms for the current user'
| def s3_set_roles(self):
| session = current.session
s3 = current.response.s3
if ('restricted_tables' in s3):
del s3['restricted_tables']
permission = self.permission
permission.clear_cache()
system_roles = self.get_system_roles()
ANONYMOUS = system_roles.ANONYMOUS
if ANONYMOUS:
session.s3.roles = ... |
'Back-end method to create roles with ACLs
@param role: display name for the role
@param description: description of the role (optional)
@param acls: list of initial ACLs to assign to this role
@param args: keyword arguments (see below)
@keyword name: a unique name for the role
@keyword hidden: hide this role completel... | def s3_create_role(self, role, description=None, *acls, **args):
| table = self.settings.table_group
hidden = args.get('hidden')
system = args.get('system')
protected = args.get('protected')
if isinstance(description, dict):
acls = ([description] + acls)
description = None
uid = args.get('uid', None)
if uid:
record = current.db((tabl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.