예제 #1
0
    def _make_clone(self, parent=None, recursive=True):
        '''Clone the current :class:`css` element and execute all
:class:`mixin` in the process.'''
        if self._clone:
            if parent is not None:
                self._set_parent(parent)
            return self
        elem = self.make(self._tag, clone=True)
        elem.parent_relationship = self.parent_relationship
        elem.comment = self.comment
        elem._attributes.extend(self._attributes)
        parent = parent if parent is not None else self.parent
        if parent is not None:
            parent = parent._make_clone(recursive=False)
        elem._set_parent(parent)
        if recursive:
            # first execute all mixins
            children = elem._children
            for tag, child in iteritems(self.children):
                if isinstance(child, mixin):
                    child(elem)
                elif tag in children:
                    children[tag].extend(child)
                else:
                    children[tag] = list(child)
            # now aggregate
            elem._children = OrderedDict()
            for tag, child_list in iteritems(children):
                for child in child_list:
                    child._make_clone(parent=elem)
        return elem
예제 #2
0
파일: base.py 프로젝트: pombredanne/djpcms
    def __init__(self, maker=None, data_stream=None,
                 cn=None, data=None, options=None,
                 css=None, **params):
        '''Initialize a widget. Usually this constructor is not invoked
directly, Instead it is called by the callable :class:`WidgetMaker` which
is a factory of :class:`Widget`.

:parameter maker: The :class:`WidgetMaker` creating this :class:`Widget`.
:parameter data_stream: set the :attr:`data_stream` attribute.
'''
        maker = maker if maker else self.maker
        if maker in default_widgets_makers:
            maker = default_widgets_makers[maker]
        if not isinstance(maker, WidgetMaker):
            maker = DefaultMaker
        self.maker = maker
        AttributeMixin.__init__(self, cn=maker.classes, data=maker.data,
                                attrs=maker.attrs, css=maker.css())
        self.addClass(cn)
        self.addData(data)
        self.css(css)
        self._data_stream = []
        attributes = maker.attributes
        for att in list(params):
            if att in attributes:
                self.addAttr(att, params.pop(att))
        self.internal.update(maker.internal)
        self.internal.update(params)
        self.tag = self.maker.tag
        self.add(data_stream)
        self.children.update(((k, maker.child_widget(c, self))\
                                for k, c in iteritems(maker.children)))
예제 #3
0
def form_data_files(request, withdata=None, method='post', initial=None):
    '''
:parameter withdata: optional flag which can be used to avoid to bind
    the form to data in the event the request method is the same as the
    form action.
'''
    method = method.lower()
    rmethod = request.method.lower()
    get_data = request.GET
    if method == 'post':
        post = request.POST
        data = post.copy()
        # extend the dat with the GET dictionary, excluding the
        data.update(((k,v) for k,v in iteritems(get_data)\
                      if k is not NEXT_KEY and k not in post))
    else:
        data = get_data.copy()
    #data = request.POST if method == 'post' else request.GET
    bind_data = None
    if withdata or (withdata is None and rmethod == method):
        bind_data = data
    if bind_data is not None:
        return bind_data, request.FILES, initial
    else:
        if initial is None:
            initial = data
        else:
            initial.update(data)
        return None, None, initial
예제 #4
0
 def _set_parent(self, parent):
     # Get the element if available
     if self.tag == 'body':
         if parent:
             raise ValueError('Body cannot have parent')
         return self
     # When switching parents, remove itself from current parent children
     if self._parent and self._parent is not parent:
         self._parent.remove(self)
     clone = self._clone
     self._parent = parent = parent or self.body()
     self._clone = parent._clone
     # If the parent is a clone, unwind mixins        
     if not clone and self._clone and self._children:
         children = self._children
         self._children = OrderedDict()
         for tag, c in iteritems(children):
             if isinstance(c, mixin):
                 c(self)
             else:
                 self._children[tag] = c
     c = parent._children.get(self.code)
     if isinstance(c, list) and self not in c:
         c.append(self)
     else:
         parent._children[self.code] = [self]
예제 #5
0
def form_data_files(request, withdata=None, method='post', initial=None):
    '''
:parameter withdata: optional flag which can be used to avoid to bind
    the form to data in the event the request method is the same as the
    form action.
'''
    method = method.lower()
    rmethod = request.method.lower()
    get_data = request.GET
    if method == 'post':
        post = request.POST
        data = post.copy()
        # extend the dat with the GET dictionary, excluding the
        data.update(((k,v) for k,v in iteritems(get_data)\
                      if k is not NEXT_KEY and k not in post))
    else:
        data = get_data.copy()
    #data = request.POST if method == 'post' else request.GET
    bind_data = None
    if withdata or (withdata is None and rmethod == method):
        bind_data = data
    if bind_data is not None:
        return bind_data, request.FILES, initial
    else:
        if initial is None:
            initial = data
        else:
            initial.update(data)
        return None, None, initial
예제 #6
0
    def _unwind(self):
        '''unwind the form by building bound fields and validating
if it is bound.'''
        if hasattr(self, '_data'):
            return
        self._data = data = {}
        self._cleaned_data = cleaned = {}
        self._errors = errors = {}
        rawdata = self.additional_data()
        if rawdata:
            rawdata.update(self.rawdata)
        else:
            rawdata = self.rawdata
        files = self._files
        self._fields = fields = []
        self._fields_dict = dfields = {}

        prefix = self.prefix
        self.initial = initial = self.initial
        is_bound = self.is_bound
        form_message = self.form_message

        # Loop over form fields
        for name, field in iteritems(self.base_fields):
            bfield = BoundField(self, field, name, self.prefix)
            key = bfield.html_name
            fields.append(bfield)
            dfields[name] = bfield
            field_value = None
            if is_bound:
                rawvalue = field_value = field.value_from_datadict(
                    rawdata, files, key)
                if rawvalue not in NOTHING:
                    self.changed = True
                    data[name] = rawvalue
                try:
                    value = bfield.clean(rawvalue)
                    func_name = 'clean_' + name
                    if hasattr(self, func_name):
                        value = getattr(self, func_name)(value)
                    cleaned[name] = value
                except ValidationError as e:
                    form_message(errors, name, to_string(e))

            elif name in initial:
                data[name] = field_value = initial[name]

            bfield.value = field_value

        if is_bound and not errors:
            # Invoke the form clean method. Usefull for last minute
            # checking or cross field checking
            try:
                self.clean()
            except ValidationError as e:
                form_message(errors, '__all__', to_string(e))
                del self._cleaned_data
        else:
            del self._cleaned_data
예제 #7
0
파일: base.py 프로젝트: pombredanne/djpcms
    def _unwind(self):
        '''unwind the form by building bound fields and validating
if it is bound.'''
        if hasattr(self,'_data'):
            return
        self._data = data = {}
        self._cleaned_data = cleaned = {}
        self._errors = errors = {}
        rawdata = self.additional_data()
        if rawdata:
            rawdata.update(self.rawdata)
        else:
            rawdata = self.rawdata
        files = self._files
        self._fields = fields = []
        self._fields_dict = dfields = {}

        prefix = self.prefix
        self.initial = initial = self.initial
        is_bound = self.is_bound
        form_message = self.form_message

        # Loop over form fields
        for name, field in iteritems(self.base_fields):
            bfield = BoundField(self, field, name, self.prefix)
            key = bfield.html_name
            fields.append(bfield)
            dfields[name] = bfield
            field_value = None
            if is_bound:
                rawvalue = field_value = field.value_from_datadict(
                                    rawdata, files, key)
                if rawvalue not in NOTHING:
                    self.changed = True
                    data[name] = rawvalue
                try:
                    value = bfield.clean(rawvalue)
                    func_name = 'clean_' + name
                    if hasattr(self, func_name):
                        value = getattr(self, func_name)(value)
                    cleaned[name] = value
                except ValidationError as e:
                    form_message(errors, name, to_string(e))

            elif name in initial:
                data[name] = field_value = initial[name]

            bfield.value = field_value

        if is_bound and not errors:
            # Invoke the form clean method. Usefull for last minute
            # checking or cross field checking
            try:
                self.clean()
            except ValidationError as e:
                form_message(errors, '__all__', to_string(e))
                del self._cleaned_data
        else:
            del self._cleaned_data
예제 #8
0
파일: base.py 프로젝트: pombredanne/djpcms
    def initials(cls):
        '''Iterator over initial field values.
Check the :attr:`Field.initial` attribute for more information.
This class method can be useful when using forms outside web applications.'''
        for name, field in iteritems(cls.base_fields):
            initial = field.get_initial(cls)
            if initial is not None:
                yield name, initial
예제 #9
0
def iterable_for_widget(data):
    if isinstance(data, dict):
        return iteritems(data)
    elif not isinstance(data, Widget) and hasattr(data,'__iter__') and\
         not is_string_or_native_string(data):
        return data
    else:
        return (data, )
예제 #10
0
파일: base.py 프로젝트: pombredanne/djpcms
def iterable_for_widget(data):
    if isinstance(data, dict):
        return iteritems(data)
    elif not isinstance(data, Widget) and hasattr(data,'__iter__') and\
         not is_string_or_native_string(data):
        return data
    else:
        return (data,)
예제 #11
0
    def initials(cls):
        '''Iterator over initial field values.
Check the :attr:`Field.initial` attribute for more information.
This class method can be useful when using forms outside web applications.'''
        for name, field in iteritems(cls.base_fields):
            initial = field.get_initial(cls)
            if initial is not None:
                yield name, initial
예제 #12
0
    def match(self, path):
        """Match a path and return ``None`` if no matching, otherwise
 a dictionary of matched variables with values. If there is more
 to be match in the path, the remaining string is placed in the
 ``__remaining__`` key of the dictionary."""
        match = self._regex.search(path)
        if match is not None:
            remaining = path[match.end() :]
            groups = match.groupdict()
            result = {}
            for name, value in iteritems(groups):
                try:
                    value = self._converters[name].to_python(value)
                except UrlException:
                    return
                result[str(name)] = value
            if remaining:
                result["__remaining__"] = remaining
            return result
예제 #13
0
    def match(self, path):
        '''Match a path and return ``None`` if no matching, otherwise
 a dictionary of matched variables with values. If there is more
 to be match in the path, the remaining string is placed in the
 ``__remaining__`` key of the dictionary.'''
        match = self._regex.search(path)
        if match is not None:
            remaining = path[match.end():]
            groups = match.groupdict()
            result = {}
            for name, value in iteritems(groups):
                try:
                    value = self._converters[name].to_python(value)
                except UrlException:
                    return
                result[str(name)] = value
            if remaining:
                result['__remaining__'] = remaining
            return result
예제 #14
0
파일: base.py 프로젝트: pombredanne/djpcms
 def _fill_initial(self):
     # Fill the initial dictionary with data from fields and from
     # the instance if available
     old_initial = self.initial
     self.initial = initial = {}
     instance = self.instance
     instance_id = instance.id if instance else None
     for name, field in iteritems(self.base_fields):
         if name in old_initial:
             value = old_initial[name]
         else:
             value = field.get_initial(self)
         # Instance with id can override the initial value
         if instance_id:
             try:
                 # First try the field method
                 value = field.value_from_instance(instance)
             except ValueError:
                 value = self.value_from_instance(instance, name, value)
         if value is not None:
             initial[name] = value
예제 #15
0
 def _fill_initial(self):
     # Fill the initial dictionary with data from fields and from
     # the instance if available
     old_initial = self.initial
     self.initial = initial = {}
     instance = self.instance
     instance_id = instance.id if instance else None
     for name, field in iteritems(self.base_fields):
         if name in old_initial:
             value = old_initial[name]
         else:
             value = field.get_initial(self)
         # Instance with id can override the initial value
         if instance_id:
             try:
                 # First try the field method
                 value = field.value_from_instance(instance)
             except ValueError:
                 value = self.value_from_instance(instance, name, value)
         if value is not None:
             initial[name] = value
예제 #16
0
    def __init__(self,
                 maker=None,
                 data_stream=None,
                 cn=None,
                 data=None,
                 options=None,
                 css=None,
                 **params):
        '''Initialize a widget. Usually this constructor is not invoked
directly, Instead it is called by the callable :class:`WidgetMaker` which
is a factory of :class:`Widget`.

:parameter maker: The :class:`WidgetMaker` creating this :class:`Widget`.
:parameter data_stream: set the :attr:`data_stream` attribute.
'''
        maker = maker if maker else self.maker
        if maker in default_widgets_makers:
            maker = default_widgets_makers[maker]
        if not isinstance(maker, WidgetMaker):
            maker = DefaultMaker
        self.maker = maker
        AttributeMixin.__init__(self,
                                cn=maker.classes,
                                data=maker.data,
                                attrs=maker.attrs,
                                css=maker.css())
        self.addClass(cn)
        self.addData(data)
        self.css(css)
        self._data_stream = []
        attributes = maker.attributes
        for att in list(params):
            if att in attributes:
                self.addAttr(att, params.pop(att))
        self.internal.update(maker.internal)
        self.internal.update(params)
        self.tag = self.maker.tag
        self.add(data_stream)
        self.children.update(((k, maker.child_widget(c, self))\
                                for k, c in iteritems(maker.children)))
예제 #17
0
 def __new__(cls, tag, *components, **attributes):
     if tag == 'body':
         elems = [cls.body()]
     elif tag:
         elems = [cls.make(tag) for tag in alltags(tag)]
     else:
         elems = [cls.make(tag)]
     parent = attributes.pop('parent', None)
     parent_relationship = attributes.pop('parent_relationship', 'child')
     comment = attributes.pop('comment', None)
     for self in elems:
         self.parent_relationship = parent_relationship
         self.comment = comment
         for name, value in iteritems(attributes):
             self[name] = value
         self._set_parent(parent)
         # Loop over components to add them to self
         for cl in components:
             if not isinstance(cl, list):
                 cl = (cl,)
             for c in cl: 
                 self.add(c)
     return elems[0] if len(elems) == 1 else elems
예제 #18
0
def definition_list(data):
    if isinstance(data, Mapping):
        data = iteritems(data)
    widget = Widget('div', cn=classes.object_definition)
    items = (Widget('dl', pair) for pair in data)
    return widget.add(items)
예제 #19
0
파일: base.py 프로젝트: pombredanne/djpcms
def update_mapping(d, u):
    for k, v in iteritems(u):
        if isinstance(v, Mapping):
            v = update_mapping(d.get(k, {}), v)
        d[k] = v
    return d
예제 #20
0
def attrsiter(attrs):
    for k, v in iteritems(attrs):
        if v is not None:
            yield " %s='%s'" % (k, escape(v, force=True))
예제 #21
0
파일: base.py 프로젝트: pombredanne/djpcms
def attrsiter(attrs):
    for k, v in iteritems(attrs):
        if v is not None:
            yield " %s='%s'" % (k, escape(v, force=True))
예제 #22
0
def update_mapping(d, u):
    for k, v in iteritems(u):
        if isinstance(v, Mapping):
            v = update_mapping(d.get(k, {}), v)
        d[k] = v
    return d
예제 #23
0
def definition_list(data):
    if isinstance(data, Mapping):
        data = iteritems(data)
    widget = Widget('div', cn=classes.object_definition)
    items = (Widget('dl', pair) for pair in data)
    return widget.add(items)