def get_linker(action, modelname=modelname): _ = get_translator().gettext label = action == "edit" and _("edit") or _("delete") return lambda item: '<a href="%s" title="%s" class="icon %s">%s</a>' % ( h.url_for(controller=controller, modelname=modelname, action=action, id=_pk(item)), label, action, label, )
def f(value, field=None): if len(value) < min_: raise ValidationError( _('Value must be at least %(min)d characters long') % {'min': min_}) if max_ is not None and len(value) > max_: raise ValidationError( _('Value must be no more than %(max)d characters long') % {'max': max_})
def email(value, field=None): """Defines a less verbose and explicit error message when validation fails""" try: email_verbose(value, field) except ValidationError: raise ValidationError(_("Invalid e-mail address"))
def file_extension(extensions=[], errormsg=None): """Validate a file extension. """ if errormsg is None: errormsg = _('Invalid file extension. Must be %s' % ', '.join(extensions)) return regex(r'^.+\.(%s)$' % '|'.join(extensions), errormsg=errormsg)
def f(value, field): if isinstance(first_password_field, (str, unicode)): fld = first_password_field else: fld = first_password_field.key if value != getattr(field.parent, fld).value: raise ValidationError(_('Passwords must match'))
def decimal_(value, field=None): """Successful if value can represent a decimal""" # the validator contract says you don't have to worry about "value is None", # but this is called from deserialize as well as validation if not value.strip(): return None try: return Decimal(value) except: raise ValidationError(_('Value is not a number'))
def float_(value, field=None): """Successful if value is a float""" # the validator contract says you don't have to worry about "value is None", # but this is called from deserialize as well as validation if value is None or not value.strip(): return None try: return float(value) except: raise ValidationError(_('Value is not a number'))
def integer(value, field=None): """Successful if value is an int""" # the validator contract says you don't have to worry about "value is None", # but this is called from deserialize as well as validation if isinstance(value, int): return value if not value.strip(): return None try: return int(value) except: raise ValidationError(_('Value is not an integer'))
def delete(self, modelname, id): """Delete an instance of the given model type""" F_ = get_translator().gettext fs = self._model_fieldsets[modelname] S = self.Session() instance = S.query(fs.model.__class__).get(id) key = _pk(instance) S.delete(instance) S.commit() message = F_(_("Deleted %s %s")) % (modelname.encode("utf-8", "ignore"), key) flash(message) redirect_to(controller=self._name, modelname=modelname, action="list", id=None)
def edit(self, modelname, id=None): """Edit (or create, if `id` is None) an instance of the given model type""" F_ = get_translator().gettext fs = self._model_fieldsets[modelname] S = self.Session() if id: instance = S.query(fs.model.__class__).get(id) c.fs = fs.bind(instance) title = "Edit" else: c.fs = fs.bind(fs.model.__class__, session=S) title = "New object" if request.method == "POST": c.fs = c.fs.bind(data=request.params) log.debug("saving %s w/ %s" % (c.fs.model.id, request.POST)) if c.fs.validate(): c.fs.sync() S.flush() if not id: # needed if the object does not exist in db if not object_session(c.fs.model): S.save(c.fs.model) message = _("Created %s %s") else: S.refresh(c.fs.model) message = _("Modified %s %s") S.commit() message = F_(message) % (modelname.encode("utf-8", "ignore"), _pk(c.fs.model)) flash(message) redirect_to(modelname=modelname, action="list", id=None) return self._engine( "admin_edit", c=c, action=title, id=id, controller=self._name, modelname=modelname, custom_css=self._custom_css, custom_js=self._custom_js, )
def regex(exp, errormsg=_('Invalid input')): """ Returns a validator that is successful if the input matches (that is, fulfils the semantics of re.match) the given expression. Expressions may be either a string or a Pattern object of the sort returned by re.compile. """ import re if type(exp) != type(re.compile('')): exp = re.compile(exp) def f(value, field=None): if not exp.match(value): raise ValidationError(errormsg) return f
def delete(self, modelname, id, format='html'): """Delete an instance of the given model type""" F_ = get_translator().gettext fs = self._model_fieldsets[modelname] S = self.Session() instance = S.query(fs.model.__class__).get(id) key = _pk(instance) S.delete(instance) S.commit() if format == 'html': message = F_(_('Deleted %s %s')) % (modelname.encode('utf-8', 'ignore'), key) flash(message) redirect(url('models', modelname=modelname)) else: return self.render_json(status=0)
def delete(self, modelname, id, format='html'): """Delete an instance of the given model type""" F_ = get_translator().gettext fs = self._model_fieldsets[modelname] S = self.Session() instance = S.query(fs.model.__class__).get(id) key = _pk(instance) S.delete(instance) S.commit() if format == 'html': message = F_(_('Deleted %s %s')) % (modelname.encode( 'utf-8', 'ignore'), key) flash(message) redirect(url('models', modelname=modelname)) else: return self.render_json(status=0)
from pylons.controllers.util import redirect import pylons.controllers.util as h from webhelpers.paginate import Page from sqlalchemy.orm import class_mapper, object_session from formalchemy import * from formalchemy.i18n import _, get_translator from formalchemy.fields import _pk from formalchemy.templates import MakoEngine import simplejson as json __all__ = ['FormAlchemyAdminController'] # misc labels _('Add') _('Edit') _('New') _('Save') _('Delete') _('Cancel') _('Models') _('Existing objects') _('New object') _('Related types') _('Existing objects') _('Create form') # templates template_dir = os.path.dirname(__file__)
def image_extension(extensions=['jpeg', 'jpg', 'gif', 'png']): """Validate an image extension. default valid extensions are jpeg, jpg, gif, png. """ errormsg = _('Invalid image file. Must be %s'%', '.join(extensions)) return file_extension(extensions, errormsg=errormsg)
def file_extension(extensions=[], errormsg=None): """Validate a file extension. """ if errormsg is None: errormsg = _('Invalid file extension. Must be %s'%', '.join(extensions)) return regex(r'^.+\.(%s)$' % '|'.join(extensions), errormsg=errormsg)
def edit(self, modelname, id=None, format='html'): """Edit (or create, if `id` is None) an instance of the given model type""" saved = 1 if id and id.endswith('.json'): id = id[:-5] format = 'json' if request.method == 'POST' or format == 'json': if id: prefix = '%s-%s' % (modelname, id) else: prefix = '%s-' % modelname if request.method == 'PUT': items = json.load(request.body_file).items() request.method = 'POST' elif '_method' not in request.POST: items = request.POST.items() format = 'json' else: items = None if items: for k, v in items: if not k.startswith(prefix): if isinstance(v, list): for val in v: request.POST.add('%s-%s' % (prefix, k), val) else: request.POST.add('%s-%s' % (prefix, k), v) fs = self._model_fieldsets[modelname] S = self.Session() if id: instance = S.query(fs.model.__class__).get(id) assert instance, id title = 'Edit' else: instance = fs.model.__class__ title = 'New object' if request.method == 'POST': F_ = get_translator().gettext c.fs = fs.bind(instance, data=request.POST, session=not id and S or None) if c.fs.validate(): c.fs.sync() S.flush() if not id: # needed if the object does not exist in db if not object_session(c.fs.model): S.add(c.fs.model) message = _('Created %s %s') else: S.refresh(c.fs.model) message = _('Modified %s %s') S.commit() saved = 0 if format == 'html': message = F_(message) % (modelname.encode( 'utf-8', 'ignore'), _pk(c.fs.model)) flash(message) redirect(url('models', modelname=modelname)) else: c.fs = fs.bind(instance, session=not id and S or None) if format == 'html': return self._engine('admin_edit', c=c, action=title, id=id, modelname=modelname, custom_css=self._custom_css, custom_js=self._custom_js) else: return self.render_json(fs=c.fs, status=saved, model=modelname)
def f(value, field=None): if len(value) > length: raise ValidationError(_('Value must be no more than %d characters long') % length)
def image_extension(extensions=["jpeg", "jpg", "gif", "png"]): """Validate an image extension. default valid extensions are jpeg, jpg, gif, png. """ errormsg = _("Invalid image file. Must be %s" % ", ".join(extensions)) return file_extension(extensions, errormsg=errormsg)
def f(value, field=None): if len(value) < min_: raise ValidationError(_('Value must be at least %(min)d characters long') % {'min': min_}) if max_ is not None and len(value) > max_: raise ValidationError(_('Value must be no more than %(max)d characters long') % {'max': max_})
def f(value, field=None): if len(value) < length: raise ValidationError(_('Value must be at least %d characters long') % length)
def required(value, field=None): """Successful if value is neither None nor the empty string (yes, including empty lists)""" if value is None or value == '': msg = isinstance(value, list) and _('Please select a value') or _( 'Please enter a value') raise ValidationError(msg)
def required(value, field=None): """Successful if value is neither None nor the empty string (yes, including empty lists)""" if value is None or value == '': msg = isinstance(value, list) and _('Please select a value') or _('Please enter a value') raise ValidationError(msg)
def email(value, field=None): """ Successful if value is a valid RFC 822 email address. Ignores the more subtle intricacies of what is legal inside a quoted region, and thus may accept some technically invalid addresses, but will never reject a valid address (which is a much worse problem). """ if not value.strip(): return None reserved = r'()<>@,;:\"[]' try: recipient, domain = value.split('@', 1) except ValueError: raise ValidationError(_('Missing @ sign')) if any([ord(ch) < 32 for ch in value]): raise ValidationError(_('Control characters present')) if any([ord(ch) > 127 for ch in value]): raise ValidationError(_('Non-ASCII characters present')) # validate recipient if not recipient: raise ValidationError(_('Recipient must be non-empty')) if recipient.endswith('.'): raise ValidationError(_("Recipient must not end with '.'")) # quoted regions, aka the reason any regexp-based validator is wrong i = 0 while i < len(recipient): if recipient[i] == '"' and (i == 0 or recipient[i - 1] == '.' or recipient[i - 1] == '"'): # begin quoted region -- reserved characters are allowed here. # (this implementation allows a few addresses not strictly allowed by rfc 822 -- # for instance, a quoted region that ends with '\' appears to be illegal.) i += 1 while i < len(recipient): if recipient[i] == '"': break # end of quoted region i += 1 else: raise ValidationError(_("Unterminated quoted section in recipient")) i += 1 if i < len(recipient) and recipient[i] != '.': raise ValidationError(_("Quoted section must be followed by '@' or '.'")) continue if recipient[i] in reserved: raise ValidationError(_("Reserved character present in recipient")) i += 1 # validate domain if not domain: raise ValidationError(_('Domain must be non-empty')) if domain.endswith('.'): raise ValidationError(_("Domain must not end with '.'")) if '..' in domain: raise ValidationError(_("Domain must not contain '..'")) if any([ch in reserved for ch in domain]): raise ValidationError(_("Reserved character present in domain"))
def edit(self, modelname, id=None, format='html'): """Edit (or create, if `id` is None) an instance of the given model type""" saved = 1 if id and id.endswith('.json'): id = id[:-5] format = 'json' if request.method == 'POST' or format == 'json': if id: prefix = '%s-%s' % (modelname, id) else: prefix = '%s-' % modelname if request.method == 'PUT': items = json.load(request.body_file).items() request.method = 'POST' elif '_method' not in request.POST: items = request.POST.items() format = 'json' else: items = None if items: for k, v in items: if not k.startswith(prefix): if isinstance(v, list): for val in v: request.POST.add('%s-%s' % (prefix, k), val) else: request.POST.add('%s-%s' % (prefix, k), v) fs = self._model_fieldsets[modelname] S = self.Session() if id: instance = S.query(fs.model.__class__).get(id) assert instance, id title = 'Edit' else: instance = fs.model.__class__ title = 'New object' if request.method == 'POST': F_ = get_translator().gettext c.fs = fs.bind(instance, data=request.POST, session=not id and S or None) if c.fs.validate(): c.fs.sync() S.flush() if not id: # needed if the object does not exist in db if not object_session(c.fs.model): S.add(c.fs.model) message = _('Created %s %s') else: S.refresh(c.fs.model) message = _('Modified %s %s') S.commit() saved = 0 if format == 'html': message = F_(message) % (modelname.encode('utf-8', 'ignore'), _pk(c.fs.model)) flash(message) redirect(url('models', modelname=modelname)) else: c.fs = fs.bind(instance, session=not id and S or None) if format == 'html': return self._engine('admin_edit', c=c, action=title, id=id, modelname=modelname, custom_css = self._custom_css, custom_js = self._custom_js) else: return self.render_json(fs=c.fs, status=saved, model=modelname)
def email(value, field=None): """ Successful if value is a valid RFC 822 email address. Ignores the more subtle intricacies of what is legal inside a quoted region, and thus may accept some technically invalid addresses, but will never reject a valid address (which is a much worse problem). """ if not value.strip(): return None reserved = r'()<>@,;:\"[]' try: recipient, domain = value.split('@', 1) except ValueError: raise ValidationError(_('Missing @ sign')) if any([ord(ch) < 32 for ch in value]): raise ValidationError(_('Control characters present')) if any([ord(ch) > 127 for ch in value]): raise ValidationError(_('Non-ASCII characters present')) # validate recipient if not recipient: raise ValidationError(_('Recipient must be non-empty')) if recipient.endswith('.'): raise ValidationError(_("Recipient must not end with '.'")) # quoted regions, aka the reason any regexp-based validator is wrong i = 0 while i < len(recipient): if recipient[i] == '"' and (i == 0 or recipient[i - 1] == '.' or recipient[i - 1] == '"'): # begin quoted region -- reserved characters are allowed here. # (this implementation allows a few addresses not strictly allowed by rfc 822 -- # for instance, a quoted region that ends with '\' appears to be illegal.) i += 1 while i < len(recipient): if recipient[i] == '"': break # end of quoted region i += 1 else: raise ValidationError( _("Unterminated quoted section in recipient")) i += 1 if i < len(recipient) and recipient[i] != '.': raise ValidationError( _("Quoted section must be followed by '@' or '.'")) continue if recipient[i] in reserved: raise ValidationError(_("Reserved character present in recipient")) i += 1 # validate domain if not domain: raise ValidationError(_('Domain must be non-empty')) if domain.endswith('.'): raise ValidationError(_("Domain must not end with '.'")) if '..' in domain: raise ValidationError(_("Domain must not contain '..'")) if any([ch in reserved for ch in domain]): raise ValidationError(_("Reserved character present in domain"))
def file_extension(extensions=[], errormsg=None): """Validate a file extension. """ if errormsg is None: errormsg = _("Invalid file extension. Must be %s" % ", ".join(extensions)) return regex(r"^.+\.(%s)$" % "|".join(extensions), errormsg=errormsg)
from pylons.controllers.util import redirect_to import pylons.controllers.util as h from webhelpers.paginate import Page from sqlalchemy.orm import class_mapper, object_session from formalchemy import * from formalchemy.i18n import _, get_translator from formalchemy.fields import _pk from formalchemy.templates import MakoEngine __all__ = ["FormAlchemyAdminController"] # misc labels _("Edit") _("Delete") _("Cancel") _("Models") _("Existing objects") _("New object") _("Related types") _("Existing objects") _("Create form") # templates template_dir = os.path.dirname(__file__) def flash(msg):