Exemple #1
0
 def __init__(
     self,
     form_class,
     model=None,
     related_name=None,
     clean=None,
     initial_length=3,
     extra_length=3,
     instances_from_related=None,
 ):
     self.form_class = form_class
     self.model = model
     self.mapper = orms.mapper(model)
     self.related_name = related_name
     self.clean = clean
     self.instances_from_related = instances_from_related
     base_fields = self.form_class.base_fields
     # Add the id field if not already available
     if "id" not in base_fields:
         base_fields["id"] = CharField(required=False, widget=HiddenInput())
     self.name = None
     self.creation_counter = FormSet.creation_counter
     self.initial_length = initial_length
     self.extra_length = extra_length
     FormSet.creation_counter += 1
     self.related_form = None
Exemple #2
0
    def for_model(self, model, all=False, start=True):
        '''Obtain a :class:`Application` for model *model*.
If the application is not available, it returns ``None``. It never fails.
If *all* is set to ``True`` it returns a list of all the :class:`Application`
for that model.'''
        if not model:
            return
        if hasattr(model, 'model'):
            model = model.model
        mapper = orms.mapper(model)
        if not mapper:
            return None
        model = mapper.model
        app = self._model_registry.get(model)
        if not app or all:
            apps = [app] if app is not None else []
            for site in self:
                if not isinstance(site,Site):
                    break
                app = site.for_model(model,all)
                if app is not None:
                    if all:
                        apps.extend(app)
                    else:
                        return app
            if all:
                if start and self.parent:
                    for a in self.parent.for_model(model,all=True,start=False):
                        if a not in apps:
                            apps.append(a)
                return apps
        else:
            return app
Exemple #3
0
    def for_model(self, model=None, all=False, root=False, name=None,
                  urlargs=None, instance=None):
        '''Create a new :class:`Request` instance for a model class. The
model can be specified directly or indirectly via the *instance* parameter.

:parameter model: model class to search.
:parameter model: all check all sites.
:parameter root: Start the search from the root site.
:parameter name: Optional view name if you require a non standard view
    (root view when instance is ``None`` or the
    :meth:`djpcms.views.Application.view_for_instance` result).
:parameter urlargs: url variables.
:parameter instance: optional instance of model.

If *instance* is provided, *model* is given by the instance class and therefore
overrides the *model* input. In addition if *name* is not given and *instance*
is available, the name is set to ``view``.
'''
        if instance is None:
            model = model or self.model
        else:
            mapper = orms.mapper(instance)
            if not mapper:
                return
            model = mapper.model
        app = self.app_for_model(model, all=all, root=root)
        return self.for_app(app, name, instance, urlargs)
Exemple #4
0
 def __init__(self,
              form_class,
              model=None,
              related_name=None,
              clean=None,
              initial_length=3,
              extra_length=3,
              instances_from_related=None):
     self.form_class = form_class
     self.model = model
     self.mapper = orms.mapper(model)
     self.related_name = related_name
     self.clean = clean
     self.instances_from_related = instances_from_related
     base_fields = self.form_class.base_fields
     # Add the id field if not already available
     if 'id' not in base_fields:
         base_fields['id'] = CharField(required = False,
                                       widget = HiddenInput())
     self.name = None
     self.creation_counter = FormSet.creation_counter
     self.initial_length = initial_length
     self.extra_length = extra_length
     FormSet.creation_counter += 1
     self.related_form = None
Exemple #5
0
    def for_model(self, model, all=False, start=True):
        '''Obtain a :class:`Application` for model *model*.
If the application is not available, it returns ``None``. It never fails.
If *all* is set to ``True`` it returns a list of all the :class:`Application`
for that model.'''
        if not model:
            return
        if hasattr(model, 'model'):
            model = model.model
        mapper = orms.mapper(model)
        if not mapper:
            return None
        model = mapper.model
        app = self._model_registry.get(model)
        if not app or all:
            apps = [app] if app is not None else []
            for site in self:
                if not isinstance(site, Site):
                    break
                app = site.for_model(model, all)
                if app is not None:
                    if all:
                        apps.extend(app)
                    else:
                        return app
            if all:
                if start and self.parent:
                    for a in self.parent.for_model(model,
                                                   all=True,
                                                   start=False):
                        if a not in apps:
                            apps.append(a)
                return apps
        else:
            return app
Exemple #6
0
def instance_field_view_value(request,
                              instance,
                              field_name,
                              name=None,
                              urlargs=None):
    '''Retrieve a view for a field of an *instance* (if that field is
an instance of a registered model) and its correspondent value.

:parameter instance: a model instance.
:parameter field_name: an *instance* field attribute name.
:parameter name: optional view name
:rtype: a two element tuple ``(view, field_value)``

It is used by :meth:`Application.viewurl`.'''
    if field_name:
        value = getattr(instance, field_name, None)
        if iscallable(value):
            value = value()
        # check that this is not an instance of a model
        mapper = orms.mapper(value)
        if mapper:
            if isinstance(value, mapper.model):
                instance = value
                value = None
            else:
                value = mapper
        elif value is None and name is None:
            return None, None
    else:
        value = None
    return request.for_model(instance=instance, name=name,
                             urlargs=urlargs), value
Exemple #7
0
    def for_model(self,
                  model=None,
                  all=False,
                  root=False,
                  name=None,
                  urlargs=None,
                  instance=None):
        '''Create a new :class:`Request` instance for a model class. The
model can be specified directly or indirectly via the *instance* parameter.

:parameter model: model class to search.
:parameter model: all check all sites.
:parameter root: Start the search from the root site.
:parameter name: Optional view name if you require a non standard view
    (root view when instance is ``None`` or the
    :meth:`djpcms.views.Application.view_for_instance` result).
:parameter urlargs: url variables.
:parameter instance: optional instance of model.

If *instance* is provided, *model* is given by the instance class and therefore
overrides the *model* input. In addition if *name* is not given and *instance*
is available, the name is set to ``view``.
'''
        if instance is None:
            model = model or self.model
        else:
            mapper = orms.mapper(instance)
            if not mapper:
                return
            model = mapper.model
        app = self.app_for_model(model, all=all, root=root)
        return self.for_app(app, name, instance, urlargs)
Exemple #8
0
 def __init__(self, **kwargs):
     cls = self.__class__
     for attname in kwargs:
         if not attname.startswith('__') and hasattr(cls, attname):
             setattr(self, attname, kwargs[attname])
     self.mapper = orms.mapper(self.model) if self.model is not None\
                      else None
     self._setmodel(self.query)
Exemple #9
0
 def __init__(self, **kwargs):
     cls = self.__class__
     for attname in kwargs:
         if not attname.startswith('__') and hasattr(cls, attname):
             setattr(self, attname, kwargs[attname])
     self.mapper = orms.mapper(self.model) if self.model is not None\
                      else None
     self._setmodel(self.query)
Exemple #10
0
def get_content_choices(bfield):
    model = bfield.form.model
    if not model:
        return []
    else:
        request = bfield.form.request
        if request:
            request = request.for_model(model)
            if request:
                return request.view.query(request)
        return orms.mapper(model).query()
Exemple #11
0
def get_content_choices(bfield):
    model = bfield.form.model
    if not model:
        return []
    else:
        request = bfield.form.request
        if request:
            request = request.for_model(model)
            if request:
                return request.view.query(request)
        return orms.mapper(model).query()
Exemple #12
0
    def __init__(self, data=None, files=None, initial=None, prefix=None,
                 model=None, instance=None, request=None, environ=None,
                 on_submit=None, **params):
        '''Initialize a :class:`Form` with *data* or *initial* values.
If *data* is not ``None`` the form will bound itself to the data, otherwise
it remains unbounded.

:parameter data: dictionary type object containing data to validate.
:parameter files: dictionary type object containing files to upload.
:parameter initial: dictionary type object containing initial values for
    form fields (see  :class:`Field`).
:parameter prefix: Optional string to use as prefix for field keys.
:parameter model: An optional model class. The model must be registered with
    the library (see :func:`djpcms.RegisterORM`).
:parameter instance: An optional instance of a model class. The model must
    be registered with the library. It sets the :attr:`instance` attribute.
:parameter request: An optional Http Request object of any kind.
    Not used by the class itself but stored in the :attr:`request`
    attribute for convenience.
    '''
        self.is_bound = data is not None or files is not None
        self.rawdata = data
        self._files = files
        if initial:
            self.initial = dict(initial.items())
        else:
            self.initial = {}
        self.prefix = prefix or ''
        self.instance = instance
        self.messages = {}
        self.request = request
        self.environ = environ
        self.params = AttributeDictionary(params)
        if environ is None:
            self.environ = getattr(request, 'environ', None)
        self.changed = False
        self.user = getattr(request,'user',None) if request else None
        if self.instance:
            model = self.instance.__class__
        if model:
            self.mapper = orms.mapper(model)
            if self.mapper is not None and not self.instance:
                self.instance = self.mapper()
        else:
            self.mapper = None
        self.form_sets = {}
        for name, fset in self.base_inlines.items():
            self.form_sets[name] = fset(self)
        self.forms = []
        if on_submit is not None:
            self.on_submit = lambda commit: on_submit(self, commit)
        if not self.is_bound:
            self._fill_initial()
Exemple #13
0
    def for_hash(self, model_hash, safe=True, all=False):
        '''Obtain a :class:`Application` for model
 model hash id. If the application is not available, it returns ``None``
 unless ``safe`` is set to ``False`` in which case it throw a
 :class:`djpcms.core.exceptions.ApplicationNotAvailable`.'''
        if model_hash in orms.model_from_hash:
            model = orms.model_from_hash[model_hash]
        else:
            if safe:
                return None
            else:
                raise ValueError('Model type %s not available' % model_hash)
        app = self.for_model(model, all=all)
        if not app:
            if not safe:
                raise ApplicationNotAvailable('Model {0} has\
 not application registered'.format(orms.mapper(model)))
        return app
Exemple #14
0
    def for_hash(self, model_hash, safe = True, all = False):
        '''Obtain a :class:`Application` for model
 model hash id. If the application is not available, it returns ``None``
 unless ``safe`` is set to ``False`` in which case it throw a
 :class:`djpcms.core.exceptions.ApplicationNotAvailable`.'''
        if model_hash in orms.model_from_hash:
            model = orms.model_from_hash[model_hash]
        else:
            if safe:
                return None
            else:
                raise ValueError('Model type %s not available' % model_hash)
        app = self.for_model(model, all = all)
        if not app:
            if not safe:
                raise ApplicationNotAvailable('Model {0} has\
 not application registered'.format(orms.mapper(model)))
        return app
Exemple #15
0
    def _load(self):
        if not self.site:
            raise UrlException("There is no site for {0}\
 application.".format(self))
        self._addroutes()
        if not self.routes:
            raise UrlException("There are no views in {0}\
 application. Try setting inherit equal to True.".format(self))
        # Set the in_nav if required
        if self.in_nav and self.root_view:
            self.root_view.in_nav = self.in_nav

        self.mapper = None if not self.model else orms.mapper(self.model)
        self.site.register_app(self)
        for view in self:
            view.parent = self
            view.appmodel = self
            if isinstance(view, View):
                if isinstance(view, ViewView):
                    if self.instance_view is not None:
                        raise UrlException('Application {0} has more\
 than one ViewView instance. Not possible.'.format(self))
                    self.instance_view = view
                    # url bit mapping
                    vars = view.route.ordered_variables()
                    if not vars:
                        raise UrlException('Application {0} has no\
 parameters to initialize objects.'.format(self.name))
                    self.model_url_bits = vars
                    if not self.url_bits_mapping:
                        self.url_bits_mapping = dict(((v, v) for v in vars))
                if self.has_plugins and view.has_plugins:
                    register_application(view)
            else:
                view.load()
        return tuple(self)
Exemple #16
0
    def _load(self):
        if not self.site:
            raise UrlException("There is no site for {0}\
 application.".format(self))
        self._addroutes()
        if not self.routes:
            raise UrlException("There are no views in {0}\
 application. Try setting inherit equal to True.".format(self))
        # Set the in_nav if required
        if self.in_nav and self.root_view:
            self.root_view.in_nav = self.in_nav

        self.mapper = None if not self.model else orms.mapper(self.model)
        self.site.register_app(self)
        for view in self:
            view.parent = self
            view.appmodel = self
            if isinstance(view, View):
                if isinstance(view, ViewView):
                    if self.instance_view is not None:
                        raise UrlException('Application {0} has more\
 than one ViewView instance. Not possible.'.format(self))
                    self.instance_view = view
                    # url bit mapping
                    vars = view.route.ordered_variables()
                    if not vars:
                        raise UrlException('Application {0} has no\
 parameters to initialize objects.'.format(self.name))
                    self.model_url_bits = vars
                    if not self.url_bits_mapping:
                        self.url_bits_mapping = dict(((v,v) for v in vars))
                if self.has_plugins and view.has_plugins:
                    register_application(view)
            else:
                view.load()
        return tuple(self)
Exemple #17
0
    def __init__(self,
                 data=None,
                 files=None,
                 initial=None,
                 prefix=None,
                 model=None,
                 instance=None,
                 request=None,
                 environ=None,
                 on_submit=None,
                 **params):
        '''Initialize a :class:`Form` with *data* or *initial* values.
If *data* is not ``None`` the form will bound itself to the data, otherwise
it remains unbounded.

:parameter data: dictionary type object containing data to validate.
:parameter files: dictionary type object containing files to upload.
:parameter initial: dictionary type object containing initial values for
    form fields (see  :class:`Field`).
:parameter prefix: Optional string to use as prefix for field keys.
:parameter model: An optional model class. The model must be registered with
    the library (see :func:`djpcms.RegisterORM`).
:parameter instance: An optional instance of a model class. The model must
    be registered with the library. It sets the :attr:`instance` attribute.
:parameter request: An optional Http Request object of any kind.
    Not used by the class itself but stored in the :attr:`request`
    attribute for convenience.
    '''
        self.is_bound = data is not None or files is not None
        self.rawdata = data
        self._files = files
        if initial:
            self.initial = dict(initial.items())
        else:
            self.initial = {}
        self.prefix = prefix or ''
        self.instance = instance
        self.messages = {}
        self.request = request
        self.environ = environ
        self.params = AttributeDictionary(params)
        if environ is None:
            self.environ = getattr(request, 'environ', None)
        self.changed = False
        self.user = getattr(request, 'user', None) if request else None
        if self.instance:
            model = self.instance.__class__
        if model:
            self.mapper = orms.mapper(model)
            if self.mapper is not None and not self.instance:
                self.instance = self.mapper()
        else:
            self.mapper = None
        self.form_sets = {}
        for name, fset in self.base_inlines.items():
            self.form_sets[name] = fset(self)
        self.forms = []
        if on_submit is not None:
            self.on_submit = lambda commit: on_submit(self, commit)
        if not self.is_bound:
            self._fill_initial()
Exemple #18
0
 def get_object(self, request, content):
     model = self.for_model(request)
     if content and model:
         return orms.mapper(model).get(id=content)
Exemple #19
0
 def _setmodel(self, query):
     # Set the model based on a query
     if not self.model and query is not None:
         self.model = getattr(query, 'model', None)
         if self.model:
             self.mapper = orms.mapper(self.model)
Exemple #20
0
 def _setmodel(self, query):
     # Set the model based on a query
     if not self.model and query is not None:
         self.model = getattr(query, 'model', None)
         if self.model:
             self.mapper = orms.mapper(self.model)
Exemple #21
0
 def get_object(self, request, content):
     model = self.for_model(request)
     if content and model:
         return orms.mapper(model).get(id=content)