Exemple #1
0
def grid_panel(context, request, data):
    model_class = data['model_class']
    grid = Grid(model_class, instances=data['items'])

    fields = []
    for column in data['columns']:
        field = column.field or grid._fields.get(column.name)
        if field is None:
            # field = AttributeField(getattr(model_class, column.name), grid)
            field = Field(column.name, fatypes.String)
        field.set(label=column.label)
        fields.append(field)

    # def checkbox(item):
    #     return u"""<input type="checkbox" name="_check" value="%d" />""" % item.id
    # field = Field('check', fatypes.String, checkbox, label=u"")
    # grid.insert(grid["id"], field)
    # fields.insert(0, field)

    model_name = data['model_name']
    def edit_link(item):
        url = request.route_url('admin_edit', model=model_name, id=item.id)
        return EDIT_LINK_TEMPLATE % dict(url=url, label='Edit')
    field = Field('edit', fatypes.String, edit_link)
    grid.append(field)
    fields.append(field)

    grid.configure(pk=1, include=fields)

    return {"grid": grid, "request": request}
Exemple #2
0
    def update_grid(self, grid):
        """Add edit and delete buttons to ``Grid``"""
        try:
            grid.edit
        except AttributeError:

            def edit_link():
                return lambda item: '''
                <form action="%(url)s" method="GET" class="ui-grid-icon ui-widget-header ui-corner-all">
                <input type="submit" class="ui-grid-icon ui-icon ui-icon-pencil" title="%(label)s" value="%(label)s" />
                </form>
                ''' % dict(url=self.request.fa_url(self.request.model_name,
                                                   _pk(item), 'edit'),
                           label=get_translator(request=self.request)('edit'))

            def delete_link():
                return lambda item: '''
                <form action="%(url)s" method="POST" class="ui-grid-icon ui-state-error ui-corner-all">
                <input type="submit" class="ui-icon ui-icon-circle-close" title="%(label)s" value="%(label)s" />
                </form>
                ''' % dict(url=self.request.fa_url(self.request.model_name,
                                                   _pk(item), 'delete'),
                           label=get_translator(request=self.request)
                           ('delete'))

            grid.append(Field('edit', fatypes.String, edit_link()))
            grid.append(Field('delete', fatypes.String, delete_link()))
            grid.readonly = True
Exemple #3
0
 def __init__(self, *args, **kwargs):
     if kwargs.get('type') in (fatypes.List, fatypes.Set):
         kwargs['multiple'] = True
         if 'options' not in kwargs:
             kwargs['options'] = lambda fs: get_node_options(fs, self.name)
     self._property = kwargs.pop('prop')
     BaseField.__init__(self, *args, **kwargs)
     if kwargs.get('type') in (fatypes.List, fatypes.Set):
         self.is_relation = True
Exemple #4
0
    def __init__(self, parent, original):
        self._original = original
        Field.__init__(self, name=original.name, value=original.value)
        self.parent = parent

        def passwords_match(value, field):
            value1 = field.renderer.params.getone(field.renderer.name)
            value2 = field.renderer.params.getone(field.renderer.name + '_confirm')
            if value1 != value2:
                raise ValidationError(_("Passwords do not match"))
        self.validators.append(passwords_match)
Exemple #5
0
    def __init__(self, parent, original):
        self._original = original
        Field.__init__(self, name=original.name, value=original.value)
        self.parent = parent

        def passwords_match(value, field):
            value1 = field.renderer.params.getone(field.renderer.name)
            value2 = field.renderer.params.getone(field.renderer.name + '_confirm')
            if value1 != value2:
                raise ValidationError(_("Passwords do not match"))
        self.validators.append(passwords_match)
Exemple #6
0
 def __init__(self, *args, **kwargs):
     self.schema = kwargs.pop('schema')
     if self.schema and 'renderer' not in kwargs:
         kwargs['renderer'] = fields.SelectFieldRenderer
     if self.schema and 'options' not in kwargs:
         if hasattr(self.schema, '_render_options'):
             kwargs['options'] = self.schema._render_options
         else:
             kwargs['options'] = lambda fs: [(d, d._id) for d in Query(self.schema).all()]
     if kwargs.get('type') == fatypes.List:
         kwargs['multiple'] = True
     BaseField.__init__(self, *args, **kwargs)
Exemple #7
0
 def __init__(self, *args, **kwargs):
     self.schema = kwargs.pop('schema')
     if self.schema and 'renderer' not in kwargs:
         kwargs['renderer'] = fields.SelectFieldRenderer
     if self.schema and 'options' not in kwargs:
         if hasattr(self.schema, '_render_options'):
             kwargs['options'] = self.schema._render_options
         else:
             kwargs['options'] = lambda fs: [(d, d._id) for d in Query(self.schema).all()]
     if kwargs.get('type') == fatypes.List:
         kwargs['multiple'] = True
     BaseField.__init__(self, *args, **kwargs)
Exemple #8
0
    def __init__(self):

        # Grid initialization
        super(EditSessionsGrid, self).__init__(Session, Session.all())

        # Creation of a customized date field to view the session's date
        self.append(create_date_field("formatted_atime", "atime", DT_FORMAT))

        # Creation of a customized field to view the session's data
        self.append(
            Field(name="formatted_data",
                  value=lambda model: "{%s}" % ",".join([
                      "%s:%s" % (k, v) for k, v in config.session_manager.
                      session_handler.store.decode(model.data).items()
                      if k != "session_id"
                  ])))

        # Grid configuration
        inc = [
            FORMATTED_ATIME_READONLY(self.formatted_atime),
            FORMATTED_DATA_READONLY(self.formatted_data),
            SESSION_ID_READONLY(self.session_id)
        ]

        self.configure(include=inc)
Exemple #9
0
    def __init__(self):

        # Grid initialization
        super(EditPollsGrid, self).__init__(
            Poll, Poll.all(joined_attrs=["choices"]))  #@UndefinedVariable

        # Creation of customized date fields to edit the poll dates
        self.append(
            create_date_field("formatted_start_dt",
                              "start_dt",
                              DT_FORMAT,
                              today_by_default=True))
        self.append(
            create_date_field("formatted_end_dt",
                              "end_dt",
                              DT_FORMAT,
                              today_by_default=False))
        self.append(
            Field(name="formatted_possible_dates",
                  value=lambda model: "[%s]" % ",".join([
                      formatting.format_date(dt, DT_FORMAT)
                      for dt in model.possible_dates
                  ])))

        # Grid configuration
        inc = [
            TITLE(self.title),
            FORMATTED_START_DT(self.formatted_start_dt),
            FORMATTED_END_DT(self.formatted_end_dt),
            FORMATTED_POSSIBLE_DATES_READONLY(self.formatted_possible_dates)
        ]
        self.configure(include=inc)
Exemple #10
0
    def __init__(self, password_token=None):

        # FieldSet initialization
        super(NewPasswordFieldSet, self).__init__(User)
        self.password_token = password_token

        # FieldSet configuration
        self.append(Field("new_password"))
        self.append(Field("new_password_confirm"))

        inc = [
            NEW_PASSWORD(self.new_password),
            NEW_PASSWORD_CONFIRM(self.new_password_confirm)
        ]
        
        self.configure(include=inc)
Exemple #11
0
 def set(self, options=[], **kwargs):
     if isinstance(options, schema.Choice):
         sourcelist = options.source.by_value.values()
         if sourcelist[0].title is None:
             options = [term.value for term in sourcelist]
         else:
             options = [(term.title, term.value) for term in sourcelist]
     return BaseField.set(self, options=options, **kwargs)
Exemple #12
0
 def set(self, options=[], **kwargs):
     if isinstance(options, schema.Choice):
         sourcelist = options.source.by_value.values()
         if sourcelist[0].title is None:
             options = [term.value for term in sourcelist]
         else:
             options = [(term.title, term.value) for term in sourcelist]
     return BaseField.set(self, options=options, **kwargs)
Exemple #13
0
    def __init__(self):
        
        # FieldSet initialization
        super(EditPasswordFieldSet, self).__init__(User)

        # FieldSet configuration
        self.append(Field("old_password"))
        self.append(Field("new_password"))
        self.append(Field("new_password_confirm"))
        
        inc = [
            OLD_PASSWORD(self.old_password),
            NEW_PASSWORD(self.new_password),
            NEW_PASSWORD_CONFIRM(self.new_password_confirm)
        ]
        
        self.configure(include=inc)
Exemple #14
0
def create_generic_date_field(name,
                              attr_getter,
                              dt_format,
                              today_by_default=True):
    """ Instanciates a generic date field associated with the format passed as a parameter """
    def value(model):
        """ Returns the model date or today's date """
        default_date = datetime.date.today() if today_by_default else None
        dt = model and attr_getter(model) or default_date
        return dt and formatting.format_date(dt, dt_format)

    return Field(name=name, value=value)
Exemple #15
0
    def __init__(self, user_token):

        # FieldSet initialization
        super(NewUserFieldSet, self).__init__(User)
        self.user_token = user_token

        # FieldSet configuration
        self.append(Field("new_email", value=user_token.email))
        self.append(Field("new_password"))
        self.append(Field("new_password_confirm"))

        inc = [
            EMAIL_REQUIRED(self.new_email),
            FIRST_NAME(self.first_name),
            LAST_NAME(self.last_name),
            PSEUDONYM(self.pseudonym),
            NEW_PASSWORD(self.new_password),
            NEW_PASSWORD_CONFIRM(self.new_password_confirm)
        ]
        
        self.configure(include=inc)
    def _validate(self):
        if self.is_readonly():
            return True

        valide = BaseField._validate(self)
        if not valide:
            return False

        value = self._deserialize()

        field = self.parent.iface[self.name]
        bound = field.bind(self.model)
        try:
            bound.validate(value)
        except schema.ValidationError, e:
            self.errors.append(e.doc())
Exemple #17
0
    def __init__(self):
        
        super(EditResultsGrid, self).__init__(Result)
        
        STATUS_OPTIONS = [(u"Présent", Result.STATUSES.P), (u"Absent", Result.STATUSES.A), (u"Peut-être", Result.STATUSES.M)]
        RANK_OPTIONS = [(u"", None)] + [(formatting.append(i, formatting.to_rank), i) for i in range(1, len(User.all()))]

        self.append(Field("pseudonym", value=lambda result: result.user.pseudonym))
        
        inc = [
            self.pseudonym.label(u"Joueur").readonly(),
            self.status.label(u"Statut").dropdown(options=STATUS_OPTIONS),
            self.buyin.label(u"Mise").validate(custom_validators.required_for([Result.STATUSES.P])).validate(custom_validators.forbidden_for([Result.STATUSES.M, Result.STATUSES.A])),
            self.rank.label(u"Classement").dropdown(options=RANK_OPTIONS).validate(custom_validators.forbidden_for([Result.STATUSES.M, Result.STATUSES.A])),
            self.profit.label(u"Gain").validate(custom_validators.forbidden_for([Result.STATUSES.M, Result.STATUSES.A])),
        ]
        
        self.configure(include=inc)
Exemple #18
0
    def _validate(self):
        if self.is_readonly():
            return True

        valide = BaseField._validate(self)
        if not valide:
            return False

        value = self._deserialize()

        if isinstance(self.type, fatypes.Unicode) and not isinstance(value, unicode):
            value = _stringify(value)

        field = self.parent.iface[self.name]
        bound = field.bind(self.model)
        try:
            bound.validate(value)
        except schema.ValidationError, e:
            self.errors.append(e.doc())
Exemple #19
0
    def _validate(self):
        if self.is_readonly():
            return True

        valide = BaseField._validate(self)
        if not valide:
            return False

        value = self._deserialize()

        if isinstance(self.type,
                      fatypes.Unicode) and not isinstance(value, unicode):
            value = _stringify(value)

        field = self.parent.iface[self.name]
        bound = field.bind(self.model)
        try:
            bound.validate(value)
        except schema.ValidationError, e:
            self.errors.append(e.doc())