Example #1
0
    def get_cms_form(cls):
        """
        Build and return Form class.

        If you want to define your custom CMS Object, you likely want to override the default CMS Form. E.g.::

            from wtforms import fields
            def get_cms_form(cls):
                form = super().get_cms_form()
                form.textfield = fields.StringField("Textfield")
                return form

        :returns:  Form Class (has to be instantiated!).
        """
        if hasattr(cls, "CMSForm"):
            return cls.CMSForm
        form_factory = OrderedFormFactory()

        form_fields = model_fields(cls,
                                   db_session=db.session,
                                   exclude=cls.auto_form_exclude)

        for key in sorted(form_fields.keys()):
            form_fields[key].kwargs['name'] = key
            form_factory.add_to_tab("Root.Main", form_fields[key])
        form_factory.add_to_tab("Root.Buttons",
                                fields.SubmitField("Save", name="Save"))
        return form_factory
Example #2
0
def model_form(model, db_session=None, base_class=Form, only=None,
    exclude=None, field_args=None, converter=None, exclude_pk=True,
    exclude_fk=True, type_name=None):
    """
    A Wrapper around :func:`wtforms.ext.sqlalchemy.orm.model_form` function to facilitate creating model
    forms using a wtforms compatible model_form call but using :class:`pyck.forms.Form`
    Create a wtforms Form for a given SQLAlchemy model class::

        from pyck.forms import model_form
        from myapp.models import User
        UserForm = model_form(User)

    :param model:
        A SQLAlchemy mapped model class.
    :param base_class:
        Base form class to extend from. Must be a ``wtforms.Form`` subclass.
    :param only:
        An optional iterable with the property names that should be included in
        the form. Only these properties will have fields.
    :param exclude:
        An optional iterable with the property names that should be excluded
        from the form. All other properties will have fields.
    :param field_args:
        An optional dictionary of field names mapping to keyword arguments used
        to construct each field object.
    :param converter:
        A converter to generate the fields based on the model properties. If
        not set, ``ModelConverter`` is used.

    """
    field_dict = model_fields(model, db_session, only, exclude, field_args, converter)
    return type(model.__name__ + 'Form', (base_class, ), field_dict)
Example #3
0
    def get_cms_form(cls):
        """
        Build and return Form class.

        If you want to define your custom CMS Object, you likely want to override the default CMS Form. E.g.::

            from wtforms import fields
            def get_cms_form(cls):
                form = super().get_cms_form()
                form.textfield = fields.StringField("Textfield")
                return form

        :returns:  Form Class (has to be instantiated!).
        """
        if hasattr(cls, "CMSForm"):
            return cls.CMSForm
        form_factory = OrderedFormFactory()

        form_fields = model_fields(cls, db_session=db.session, exclude=cls.auto_form_exclude)

        for key in sorted(form_fields.keys()):
            form_fields[key].kwargs['name'] = key
            form_factory.add_to_tab("Root.Main", form_fields[key])
        form_factory.add_to_tab("Root.Buttons", fields.SubmitField("Save", name="Save"))
        return form_factory
Example #4
0
def model_form(model, db_session=None, base_class=Form, only=None,
    exclude=None, field_args=None, converter=None, exclude_pk=True,
    exclude_fk=True, type_name=None, fields_override=None):
    """
    Create a wtforms Form for a given SQLAlchemy model class::

        from wtalchemy.orm import model_form
        from myapp.models import User
        UserForm = model_form(User)

    :param model:
        A SQLAlchemy mapped model class.
    :param db_session:
        An optional SQLAlchemy Session.
    :param base_class:
        Base form class to extend from. Must be a ``wtforms.Form`` subclass.
    :param only:
        An optional iterable with the property names that should be included in
        the form. Only these properties will have fields.
    :param exclude:
        An optional iterable with the property names that should be excluded
        from the form. All other properties will have fields.
    :param field_args:
        An optional dictionary of field names mapping to keyword arguments used
        to construct each field object.
    :param converter:
        A converter to generate the fields based on the model properties. If
        not set, ``ModelConverter`` is used.
    :param exclude_pk:
        An optional boolean to force primary key exclusion.
    :param exclude_fk:
        An optional boolean to force foreign keys exclusion.
    :param type_name:
        An optional string to set returned type name.
    """
    class ModelForm(base_class):
        """Sets object as form attribute."""
        def __init__(self, *args, **kwargs):
            if 'obj' in kwargs:
                self._obj = kwargs['obj']
            super(ModelForm, self).__init__(*args, **kwargs)

    if not exclude:
        exclude = []
    model_mapper = model.__mapper__
    for prop in model_mapper.iterate_properties:
        if not hasattr(prop, 'direction') and prop.columns[0].primary_key:
            if exclude_pk:
                exclude.append(prop.key)
        if hasattr(prop, 'direction') and  exclude_fk and \
                prop.direction.name != 'MANYTOMANY':
            for pair in prop.local_remote_pairs:
                exclude.append(pair[0].key)
    type_name = type_name or str(model.__name__ + 'Form')
    field_dict = model_fields(model, db_session, only, exclude, field_args,
        converter)
    if fields_override:
        field_dict.update(fields_override)
    return type(type_name, (ModelForm, ), field_dict)
Example #5
0
def model_form(model,
               db_session=None,
               base_class=Form,
               only=None,
               exclude=None,
               field_args=None,
               converter=None,
               exclude_pk=True,
               exclude_fk=True,
               type_name=None):
    """
    A Wrapper around :func:`wtforms.ext.sqlalchemy.orm.model_form` function to facilitate creating model
    forms using a wtforms compatible model_form call but using :class:`pyck.forms.Form`
    Create a wtforms Form for a given SQLAlchemy model class::

        from pyck.forms import model_form
        from myapp.models import User
        UserForm = model_form(User)

    :param model:
        A SQLAlchemy mapped model class.
    :param base_class:
        Base form class to extend from. Must be a ``wtforms.Form`` subclass.
    :param only:
        An optional iterable with the property names that should be included in
        the form. Only these properties will have fields.
    :param exclude:
        An optional iterable with the property names that should be excluded
        from the form. All other properties will have fields.
    :param field_args:
        An optional dictionary of field names mapping to keyword arguments used
        to construct each field object.
    :param converter:
        A converter to generate the fields based on the model properties. If
        not set, ``ModelConverter`` is used.

    """
    field_dict = model_fields(model, db_session, only, exclude, field_args,
                              converter)
    return type(model.__name__ + 'Form', (base_class, ), field_dict)
Example #6
0
def model_form(model,
               db_session=None,
               base_class=Form,
               only=None,
               exclude=None,
               field_args=None,
               converter=None,
               exclude_pk=True,
               exclude_fk=True,
               type_name=None,
               fields_override=None):
    """
    Create a wtforms Form for a given SQLAlchemy model class::

        from wtalchemy.orm import model_form
        from myapp.models import User
        UserForm = model_form(User)

    :param model:
        A SQLAlchemy mapped model class.
    :param db_session:
        An optional SQLAlchemy Session.
    :param base_class:
        Base form class to extend from. Must be a ``wtforms.Form`` subclass.
    :param only:
        An optional iterable with the property names that should be included in
        the form. Only these properties will have fields.
    :param exclude:
        An optional iterable with the property names that should be excluded
        from the form. All other properties will have fields.
    :param field_args:
        An optional dictionary of field names mapping to keyword arguments used
        to construct each field object.
    :param converter:
        A converter to generate the fields based on the model properties. If
        not set, ``ModelConverter`` is used.
    :param exclude_pk:
        An optional boolean to force primary key exclusion.
    :param exclude_fk:
        An optional boolean to force foreign keys exclusion.
    :param type_name:
        An optional string to set returned type name.
    """
    class ModelForm(base_class):
        """Sets object as form attribute."""
        def __init__(self, *args, **kwargs):
            if 'obj' in kwargs:
                self._obj = kwargs['obj']
            super(ModelForm, self).__init__(*args, **kwargs)

    if not exclude:
        exclude = []
    model_mapper = model.__mapper__
    for prop in model_mapper.iterate_properties:
        if not hasattr(prop, 'direction') and prop.columns[0].primary_key:
            if exclude_pk:
                exclude.append(prop.key)
        if hasattr(prop, 'direction') and  exclude_fk and \
                prop.direction.name != 'MANYTOMANY':
            for pair in prop.local_remote_pairs:
                exclude.append(pair[0].key)
    type_name = type_name or str(model.__name__ + 'Form')
    field_dict = model_fields(model, db_session, only, exclude, field_args,
                              converter)
    if fields_override:
        field_dict.update(fields_override)
    return type(type_name, (ModelForm, ), field_dict)
Example #7
0
def dojo_model_form(model,
                    db_session=None,
                    base_class=Form,
                    only=None,
                    exclude=None,
                    field_args=None,
                    converter=None,
                    exclude_pk=False,
                    exclude_fk=False,
                    type_name=None):
    """
    A Wrapper around :func:`wtforms.ext.sqlalchemy.orm.model_form` function to facilitate creating model
    forms using a wtforms compatible model_form call but using :class:`pyck.forms.Form` and :module:`WTDojo`
    form components

    Create a wtforms Form for a given SQLAlchemy model class::

        from pyck.forms import dojo_model_form
        from myapp.models import User
        UserForm = dojo_model_form(User)

    :param model:
        A SQLAlchemy mapped model class.
    :param base_class:
        Base form class to extend from. Must be a ``wtforms.Form`` subclass.
    :param only:
        An optional iterable with the property names that should be included in
        the form. Only these properties will have fields.
    :param exclude:
        An optional iterable with the property names that should be excluded
        from the form. All other properties will have fields.
    :param field_args:
        An optional dictionary of field names mapping to keyword arguments used
        to construct each field object.
    :param converter:
        A converter to generate the fields based on the model properties. If
        not set, ``ModelConverter`` is used.
    :param exclude_pk:
        An optional boolean to force primary key exclusion.
    :param exclude_fk:
        An optional boolean to force foreign keys exclusion.
    :param type_name:
        An optional string to set returned type name.

    """
    class DojoModelForm(base_class):
        """Sets object as form attribute."""
        def __init__(self, *args, **kwargs):
            if 'obj' in kwargs:
                self._obj = kwargs['obj']
            super(DojoModelForm, self).__init__(*args, **kwargs)

    if not exclude:
        exclude = []
    model_mapper = model.__mapper__

    for prop in model_mapper.iterate_properties:
        if not hasattr(
                prop,
                'columns'):  # ignore relationships and other non-field columns
            continue

        # if it's primary key and is not foreign key
        if 0 == len(
                prop.columns[0].foreign_keys) and prop.columns[0].primary_key:
            if exclude_pk:
                exclude.append(prop.key)

        # if it's foreign key but not many to many
        if len(prop.columns[0].foreign_keys) > 0 and exclude_fk:
            if not prop.is_primary():
                exclude.append(prop.key)

    type_name = type_name or str(model.__name__ + 'Form')
    converter = converter or DojoModelConverter()

    field_dict = model_fields(model,
                              db_session,
                              only,
                              exclude,
                              field_args,
                              converter,
                              exclude_pk=exclude_pk,
                              exclude_fk=exclude_fk)
    return type(type_name, (base_class, ), field_dict)
Example #8
0
def dojo_model_form(model, db_session=None, base_class=Form, only=None,
                    exclude=None, field_args=None, converter=None, exclude_pk=False,
                    exclude_fk=False, type_name=None):
    """
    A Wrapper around :func:`wtforms.ext.sqlalchemy.orm.model_form` function to facilitate creating model
    forms using a wtforms compatible model_form call but using :class:`pyck.forms.Form` and :module:`WTDojo`
    form components

    Create a wtforms Form for a given SQLAlchemy model class::

        from pyck.forms import dojo_model_form
        from myapp.models import User
        UserForm = dojo_model_form(User)

    :param model:
        A SQLAlchemy mapped model class.
    :param base_class:
        Base form class to extend from. Must be a ``wtforms.Form`` subclass.
    :param only:
        An optional iterable with the property names that should be included in
        the form. Only these properties will have fields.
    :param exclude:
        An optional iterable with the property names that should be excluded
        from the form. All other properties will have fields.
    :param field_args:
        An optional dictionary of field names mapping to keyword arguments used
        to construct each field object.
    :param converter:
        A converter to generate the fields based on the model properties. If
        not set, ``ModelConverter`` is used.
    :param exclude_pk:
        An optional boolean to force primary key exclusion.
    :param exclude_fk:
        An optional boolean to force foreign keys exclusion.
    :param type_name:
        An optional string to set returned type name.

    """

    class DojoModelForm(base_class):
        """Sets object as form attribute."""
        def __init__(self, *args, **kwargs):
            if 'obj' in kwargs:
                self._obj = kwargs['obj']
            super(DojoModelForm, self).__init__(*args, **kwargs)

    if not exclude:
        exclude = []
    model_mapper = model.__mapper__

    for prop in model_mapper.iterate_properties:
        if not hasattr(prop, 'columns'):  # ignore relationships and other non-field columns
            continue

        # if it's primary key and is not foreign key
        if 0 == len(prop.columns[0].foreign_keys) and prop.columns[0].primary_key:
            if exclude_pk:
                exclude.append(prop.key)

        # if it's foreign key but not many to many
        if len(prop.columns[0].foreign_keys) > 0 and exclude_fk:
            if not prop.is_primary():
                exclude.append(prop.key)

    type_name = type_name or str(model.__name__ + 'Form')
    converter = converter or DojoModelConverter()
    
    field_dict = model_fields(model, db_session, only, exclude, field_args, converter, exclude_pk=exclude_pk, exclude_fk=exclude_fk)
    return type(type_name, (base_class, ), field_dict)