Example #1
0
    def test_sequencesequenceinteger_string_conversion(self):
        type = schemaish.Sequence(schemaish.Sequence(schemaish.Integer()))
        value = [[1, 2, 3], [4, 5, 6]]
        expected = '1,2,3\n4,5,6'
        actual = string_converter(type).from_type(value)
        self.assertEquals(actual, expected)

        value, expected = expected, value
        actual = string_converter(type).to_type(value)
        self.assertEquals(actual, expected)
Example #2
0
File: members.py Project: zagy/karl
 def form_fields(self):
     return [
         ('users',
          schemaish.Sequence(
              schemaish.String(validator=validator.Required()))),
         ('text', schemaish.String()),
     ]
Example #3
0
File: members.py Project: zagy/karl
 def form_fields(self):
     email = schemaish.String(validator=validator.Email())
     return [
         ('email_addresses',
          schemaish.Sequence(email, validator=validator.Required())),
         ('text', schemaish.String()),
     ]
Example #4
0
 def _schema(self):
     return schemaish.Structure([
         ('seq',
          schemaish.Sequence(
              schemaish.Structure([
                  ('foo', schemaish.String(validator=validatish.Required()))
              ]))),
     ])
Example #5
0
 def test_unicode_in_template(self):
     # Check that new item template encoding is ok with unicode characters.
     schema = schemaish.Structure([
         ('seq', schemaish.Sequence(schemaish.String()))
     ])
     form = formish.Form(schema)
     form['seq.*'].widget = formish.SelectChoice(
         options=[('GBP', '£'.decode('utf-8'))])
     form()
Example #6
0
    def test_sequenceboolean_string_conversion(self):
        type = schemaish.Sequence(schemaish.Boolean())
        value = [True, False, True, True]
        expected = 'True,False,True,True'
        actual = string_converter(type).from_type(value)
        self.assertEquals(actual, expected)

        value, expected = expected, value
        actual = string_converter(type).to_type(value)
        self.assertEquals(actual, expected)
Example #7
0
    def test_sequencestring_json_conversion(self):
        type = schemaish.Sequence(schemaish.Integer())
        value = [1, 2, 3, 4]
        expected = value
        actual = json_converter(type).from_type(value)
        self.assertEquals(actual, expected)

        value, expected = expected, value
        actual = json_converter(type).to_type(value)
        self.assertEquals(actual, expected)
Example #8
0
 def test_renders_with_options(self):
     schema = schemaish.Structure()
     schema.add('foo', schemaish.Sequence(schemaish.String()))
     form = formish.Form(schema)
     form['foo'].widget = formish.CheckboxMultiChoice(options=[('opt1',
                                                                'Opt #1')])
     html = form()
     assert 'foo' in html
     assert 'opt1' in html
     assert 'Opt #1' in html
Example #9
0
    def test_sequencetupleintegerstring_string_conversion(self):
        type = schemaish.Sequence(
            schemaish.Tuple((schemaish.Integer(), schemaish.String())))
        value = [(1, '1'), (2, '2')]
        expected = '1,1\n2,2'

        actual = string_converter(type).from_type(value)
        self.assertEquals(actual, expected)

        value, expected = expected, value
        actual = string_converter(type).to_type(value)
        self.assertEquals(actual, expected)
Example #10
0
    def test_complex_form(self):

        one = schemaish.Structure([
            ("a", schemaish.String(validator=v.All(v.Email(), v.Required()))),
            ("b", schemaish.String()),
            ("c", schemaish.Sequence(schemaish.Integer()))
        ])
        two = schemaish.Structure([("a", schemaish.String()), ("b", schemaish.Date()),\
                         ('c', schemaish.Sequence(schemaish.String())), ("d", schemaish.String()), \
                         ("e", schemaish.Integer(validator=v.Required())), ("f", schemaish.String(validator=v.Required())) ])
        schema = schemaish.Structure([("one", one), ("two", two)])
        f = formish.Form(schema, name="form", add_default_action=False)

        f['one.b'].widget = formish.TextArea()
        f['two.a'].widget = formish.SelectChoice(
            [('opt1', "Options 1"), ('opt2', "Option 2")],
            none_option=('-select option-', None))
        f['two.b'].widget = formish.DateParts()
        f['two.c'].widget = formish.CheckboxMultiChoice([('opt1', "Options 1"),
                                                         ('opt2', "Option 2")])
        f['two.d'].widget = formish.RadioChoice([('opt1', "Options 1"),
                                                 ('opt2', "Option 2")])
        f['two.f'].widget = formish.CheckedPassword()

        f.add_action('submit', "Submit Me")
        f.defaults = {
            'one': {
                'a': 'ooteenee',
                'c': ['3', '4', '5']
            },
            'two': {
                'a': 'opt1',
                'b': date(1966, 1, 3),
                'c': ['opt2'],
                'd': 'opt2'
            }
        }
        f()
Example #11
0
class InvoiceSchema(schemaish.Structure):

    customer_contact_id = schemaish.Integer(validator=validator.Required())
    project_description = schemaish.String(validator=validator.Required())
    date = schemaish.Date(validator=validator.Required())
    invoice_number = schemaish.Integer()
    recurring_term = schemaish.Integer()
    recurring_stop = schemaish.Date()
    payment_term = schemaish.Integer(validator=validator.Required())
    currency = schemaish.String(validator=validator.Required())
    tax = schemaish.Float()
    payment_date = schemaish.Date()
    item_list = schemaish.Sequence(invoice_item_schema,
                                   validator=validatish.Length(min=1))
Example #12
0
File: members.py Project: zagy/karl
    def form_fields(self):
        class Member(schemaish.Structure):
            name = schemaish.String()
            title = schemaish.String()
            moderator = schemaish.Boolean()
            member = schemaish.String()
            resend = schemaish.Boolean()
            remove = schemaish.Boolean()

        members = schemaish.Sequence(Member())
        members.title = ''
        num_moderators = len(self.community.moderator_names)
        members.num_moderators = num_moderators
        return [('members', members)]
Example #13
0
File: members.py Project: zagy/karl
    def form_fields(self):
        required = validator.Required()
        min_pw_length = int(get_setting(self.context, 'min_pw_length', 6))
        pwlen = validator.Length(min_pw_length)
        username = karlvalidators.RegularExpression(
            r'^[\w-]+$',
            'Username must contain only letters, numbers, and dashes')
        fields = [
            ('username',
             schemaish.String(validator=validator.All(required, username))),
            ('password',
             schemaish.String(validator=validator.All(required, pwlen))),
            ('password_confirm',
             schemaish.String(validator=validator.All(required, pwlen))),
            ('firstname', schemaish.String(validator=required)),
            ('lastname', schemaish.String(validator=required)),
            ('phone', schemaish.String()),
            ('extension', schemaish.String()),
            ('organization', schemaish.String()),
            (
                'country',
                schemaish.String(validator=validator.All(
                    validator.OneOf(countries.as_dict.keys()),
                    validator.Required()), ),
            ),
            ('location', schemaish.String()),
            ('department', schemaish.String()),
            ('position', schemaish.String()),
            ('websites',
             schemaish.Sequence(schemaish.String(validator=validator.URL()))),
            ('languages', schemaish.String()),
            ('biography', schemaish.String()),
            ('photo', schemaish.File()),
            ('date_format',
             schemaish.String(
                 validator=validator.OneOf(cultures.as_dict.keys()))),
        ]

        r = queryMultiAdapter((self.context, self.request),
                              IInvitationBoilerplate)
        if r is None:
            r = DefaultInvitationBoilerplate(self.context)
        if r.terms_and_conditions:
            fields.append(('terms_and_conditions',
                           schemaish.Boolean(validator=validator.Equal(True))))
        if r.privacy_statement:
            fields.append(('accept_privacy_policy',
                           schemaish.Boolean(validator=validator.Equal(True))))
        return fields
Example #14
0
class TestSequenceFormData(unittest.TestCase):

    schema = schemaish.Structure()
    schema.add('a', schemaish.Sequence(schemaish.String(title='bee')))

    def test_widgets(self):
        form = formish.Form(self.schema, 'sequences')
        form.defaults = {'a': ['1', '2']}
        assert isinstance(form['a.0'].widget.widget, formish.Input)
        form['a.*'].widget = formish.TextArea()
        assert isinstance(form['a.0'].widget.widget, formish.TextArea)

    def test_widgets_before_data(self):
        form = formish.Form(self.schema, 'sequences')
        form['a.*'].widget = formish.TextArea()
        form.defaults = {'a': ['1', '2']}
        assert isinstance(form['a.0'].widget.widget, formish.TextArea)
Example #15
0
class ActionStructure(BaseStructure):

    label = schemaish.String()
    expr = schemaish.String()
    guard_expr = schemaish.String()
    css_class = schemaish.String()
    group = schemaish.String()
    content = schemaish.Sequence(schemaish.String())

    _widgets = copy.copy(BaseStructure._widgets)
    _widgets.update({
        'content': {
            'widget': formish.CheckboxMultiChoice,
            'kwargs': {
                'options': list_content_types,
            },
        }
    })
Example #16
0
from karl.events import ObjectModifiedEvent
from karl.events import ObjectWillBeModifiedEvent
from karl.models.interfaces import IIntranets
from karl.utilities import lock
from karl.utils import get_layout_provider
from karl.views.api import TemplateAPI
from karl.views.forms import widgets

marker_field = schemaish.String(
    title='Marker',
    description='Customize what flavor of folder this is by choosing one of '
    'the following markers.')

keywords_field = schemaish.Sequence(
    schemaish.String(),
    title='Search Keywords',
    description='This document will be shown first for searches for any of '
    'these keywords')

weight_field = schemaish.Integer(
    title='Search Weight',
    description='Modify the relative importance of this document in search '
    'results.')

marker_options = [
    ('', 'No Marker'),
    ('reference_manual', 'Reference Manual'),
    ('network_events', 'Network Events'),
    ('network_news', 'Network News'),
]
Example #17
0
from karl.views.forms import validators as karlvalidators
from karl.views.versions import format_local_date

from karl.content.interfaces import IWiki
from karl.content.interfaces import IWikiPage
from karl.content.models.wiki import WikiPage
from karl.content.views.utils import extract_description

from karl.security.workflow import get_security_states

_wiki_text_help = """You can create a new page by naming it and surrounding
the name with ((double parentheses)). When you save the page, the contents
of the parentheses will have a small + link next to it, which you can click
to create a new page with that name."""

tags_field = schemaish.Sequence(schemaish.String())
text_field = schemaish.String(
    title='Body text',
    description=_wiki_text_help,
)
sendalert_field = schemaish.Boolean(
    title='Send email alert to community members?')
security_field = schemaish.String(
    description=('Items marked as private can only be seen by '
                 'members of this community.'))


def redirect_to_front_page(context, request):

    front_page = context['front_page']
    location = resource_url(front_page, request)
Example #18
0
    return dict(
        api=api,
        actions=actions,
        comments=comments,
        attachments=fetch_attachments(context['attachments'], request),
        head_data=convert_to_script(client_json_data),
        comment_form=comment_form,
        post_url=post_url,
        byline_info=byline_info,
        backto=backto,
        security_states=security_states,
    )


tags_field = schemaish.Sequence(schemaish.String())
text_field = schemaish.String()
sendalert_field = schemaish.Boolean(
    title='Send email alert to community members?')
security_field = schemaish.String(
    description=('Items marked as private can only be seen by '
                 'members of this community.'))
attachments_field = schemaish.Sequence(
    schemaish.File(),
    title='Attachments',
)


class AddBlogEntryFormController(object):
    def __init__(self, context, request):
        self.context = context
Example #19
0
    )
    for docid in docids:
        model = resolver(docid)
        if model is not None:
            if model is not context:
                adapted = getMultiAdapter((model, request), IGridEntryInfo)
                related.append(adapted)

    return {'items': related}


security_field = schemaish.String(
    description=('Items marked as private can only be seen by '
                 'members of this community.'))

tags_field = schemaish.Sequence(schemaish.String())

description_field = schemaish.String(
    description=('This description will appear in search results and '
                 'on the community listing page.  Please limit your '
                 'description to 100 words or less'),
    validator=validator.All(validator.Length(max=500), validator.Required()))

text_field = schemaish.String(
    description=('This text will appear on the Overview page for this '
                 'community.  You can use this to describe the '
                 'community or to make a special announcement.'))

tools_field = schemaish.Sequence(
    attr=schemaish.String(),
    description='Select which tools to enable on this community.')
Example #20
0
    return photo_from_filestore_view(context, request, 'add-user')


firstname_field = schemaish.String(validator=validator.Required(),
                                   title='First Name')
lastname_field = schemaish.String(validator=validator.Required(),
                                  title='Last Name')
phone_field = schemaish.String(title='Phone Number')
extension_field = schemaish.String()
fax_field = schemaish.String(title='Fax Number')
department_field = schemaish.String()
position_field = schemaish.String()
organization_field = schemaish.String()
location_field = schemaish.String()
country_field = schemaish.String(validator=validator.Required())
websites_field = schemaish.Sequence(
    schemaish.String(validator=karlvalidators.WebURL()))
languages_field = schemaish.String()
photo_field = schemaish.File()
biography_field = schemaish.String()
date_format_field = schemaish.String(title='Preferred Date Format')


class EditProfileFormController(object):
    """
    Formish controller for the profile edit form.  Also the base class
    for the controllers for the admin profile edit and add user forms.
    """
    simple_field_names = [
        "firstname",
        "lastname",
        "email",
Example #21
0
 def test_sequence_error(self):
     self._test(
         schemaish.Structure([('sequence',
                               schemaish.Sequence(schemaish.String()))]),
         'sequence')
Example #22
0
class InvoiceSchema(schemaish.Structure):
    payment_term = schemaish.Integer(
        validator=validator.All(validator.Required(), validator.Range(min=1)))
    note = schemaish.String()
    entries = schemaish.Sequence(attr=InvoiceEntrySchema())
Example #23
0
]


class EditSectionColumnFormController(EditBase):
    page_title = 'Edit Section Column'
    schema = section_column_schema


class AddSectionColumnFormController(AddBase):
    page_title = 'Add Section Column'
    schema = section_column_schema
    factory = PeopleSectionColumn


report_filter_schema = [
    ('values', schemaish.Sequence(schemaish.String())),
]


class AddCategoryReportFilterFormController(AddBase):
    page_title = 'Add Category Report Filter'
    schema = report_filter_schema
    factory = PeopleReportCategoryFilter

    def form_widgets(self, schema):
        widgets = {
            'values':
            formish.TextArea(rows=5, converter_options={'delimiter': '\n'}),
        }
        return widgets
Example #24
0
]


class EditSectionColumnFormController(EditBase):
    page_title = 'Edit Section Column'
    schema = section_column_schema


class AddSectionColumnFormController(AddBase):
    page_title = 'Add Section Column'
    schema = section_column_schema
    factory = PeopleSectionColumn


report_filter_schema = [
    ('values', schemaish.Sequence(schemaish.String())),
]


class AddCategoryReportFilterFormController(AddBase):
    page_title = 'Add Category Report Filter'
    schema = report_filter_schema
    factory = PeopleReportCategoryFilter

    def form_widgets(self, schema):
        widgets = {
            'values':
            formish.TextArea(rows=5, converter_options={'delimiter': '\n'}),
        }
        return widgets
Example #25
0
class RootStructure(schemaish.Structure):
    def __init__(self, context, *args, **kw):
        self.__context = context
        super(RootStructure, self).__init__(*args, **kw)

    name = schemaish.String()
    title = schemaish.String()
    description = schemaish.String()
    site_title = schemaish.String()
    body = schemaish.String()
    email = schemaish.String()
    analytics_code = schemaish.String()
    verification_code = schemaish.String()
    copyright_statement = schemaish.String()
    thumbnail_size = schemaish.Sequence(schemaish.Integer())

    _widgets = {
        'description': {
            'widget': formish.TextArea,
            'args': [],
            'kwargs': {
                'cols': 80,
                'rows': 5,
                'empty': ''
            },
        },
        'body': {
            'widget': formish.TextArea,
            'args': [],
            'kwargs': {
                'cols': 80,
                'rows': 15,
                'empty': ''
            },
        },
        'analytics_code': {
            'widget': formish.TextArea,
            'args': [],
            'kwargs': {
                'cols': 80,
                'rows': 5,
                'empty': ''
            },
        },
        'verification_code': {
            'widget': formish.TextArea,
            'args': [],
            'kwargs': {
                'cols': 80,
                'rows': 5,
                'empty': ''
            },
        },
        'thumbnail_size': {
            'widget': formish.TextArea,
            'args': [],
            'kwargs': {
                'cols': 10,
                'rows': 3,
                'empty': ''
            },
        },
    }
Example #26
0
class BaseInvitationFormController(object):
    fields = {
        'firstname':
        schemaish.String(validator=validator.Required()),
        'lastname':
        schemaish.String(validator=validator.Required()),
        'phone':
        schemaish.String(),
        'extension':
        schemaish.String(),
        'organization':
        schemaish.String(),
        'country':
        schemaish.String(validator=validator.All(
            validator.OneOf(countries.as_dict.keys()),
            validator.Required()), ),
        'location':
        schemaish.String(),
        'department':
        schemaish.String(),
        'position':
        schemaish.String(),
        'websites':
        schemaish.Sequence(schemaish.String(validator=validator.URL())),
        'languages':
        schemaish.String(),
        'biography':
        schemaish.String(),
        'photo':
        schemaish.File(),
        'date_format':
        schemaish.String(validator=validator.OneOf(cultures.as_dict.keys()))
    }

    def __init__(self, context, request):
        self.context = context
        self.request = request
        self.profiles = find_profiles(context)
        self.api = TemplateAPI(context, request)
        self.filestore = get_filestore(context, request, 'accept-invitation')

    @property
    def description(self):
        system_name = get_setting(self.context, 'title', 'KARL')
        return ('You have been invited to join the "%s".  Please begin '
                'by creating a login with profile information.' % system_name)

    def form_fields(self):
        min_pw_length = int(get_setting(self.context, 'min_pw_length', 6))
        pwlen = validator.Length(min_pw_length)
        username = karlvalidators.RegularExpression(
            r'^[\w-]+$',
            'Username must contain only letters, numbers, and dashes')
        fields = [
            ('username',
             schemaish.String(
                 validator=validator.All(validator.Required(), username))),
            ('password',
             schemaish.String(
                 validator=validator.All(validator.Required(), pwlen))),
            ('password_confirm',
             schemaish.String(
                 validator=validator.All(validator.Required(), pwlen))),
            ('firstname', schemaish.String(validator=validator.Required())),
            ('lastname', schemaish.String(validator=validator.Required()))
        ]
        member_fields = get_setting(self.context, 'member_fields')
        for field_name in member_fields:
            if field_name in self.fields:
                fields.append((field_name, self.fields[field_name]))

        r = queryMultiAdapter((self.context, self.request),
                              IInvitationBoilerplate)
        if r is None:
            r = DefaultInvitationBoilerplate(self.context)
        if r.terms_and_conditions:
            fields.append(('terms_and_conditions',
                           schemaish.Boolean(validator=validator.Equal(True))))
        if r.privacy_statement:
            fields.append(('accept_privacy_policy',
                           schemaish.Boolean(validator=validator.Equal(True))))
        return fields

    def form_widgets(self, fields):
        default_icon = self.api.static_url + '/images/defaultUser.gif'
        system_name = get_setting(self.context, 'title', 'KARL')
        widgets = {
            'biography':
            karlwidgets.RichTextWidget(),
            'password':
            formish.Password(),
            'password_confirm':
            formish.Password(),
            'country':
            formish.SelectChoice(countries),
            'photo':
            karlwidgets.PhotoImageWidget(filestore=self.filestore,
                                         url_base=resource_url(
                                             self.context, self.request,
                                             'photo'),
                                         image_thumbnail_default=default_icon),
            'date_format':
            formish.SelectChoice(cultures),
            'websites':
            formish.TextArea(rows=3, converter_options={'delimiter': '\n'}),
        }

        r = queryMultiAdapter((self.context, self.request),
                              IInvitationBoilerplate)
        if r is None:
            r = DefaultInvitationBoilerplate(self.context)
        terms_text = r.terms_and_conditions
        if terms_text:
            widgets['terms_and_conditions'] = (karlwidgets.AcceptFieldWidget(
                terms_text, 'the %s Terms and Conditions' % system_name))
        privacy_text = r.privacy_statement
        if privacy_text:
            widgets['accept_privacy_policy'] = (karlwidgets.AcceptFieldWidget(
                privacy_text, 'the %s Privacy Policy' % system_name))
        return widgets

    def handle_cancel(self):
        return HTTPFound(location=resource_url(self.context, self.request))

    def get_groups(self):
        return []

    def handle_submit(self, converted):
        context = self.context
        request = self.request
        users = find_users(context)
        profiles = self.profiles

        password = converted['password']
        password_confirm = converted['password_confirm']

        if password != password_confirm:
            msg = 'Mismatched password and confirm'
            raise ValidationError(password_confirm=msg, password=msg)

        username = converted['username']
        if username in profiles:
            raise ValidationError(username='******')

        groups = self.get_groups()
        users.add(username, username, password, groups)
        remember_headers = remember(request, username)

        data = dict(firstname=converted['firstname'],
                    lastname=converted['lastname'],
                    email=context.email)
        for field_name in get_setting(self.context, 'member_fields'):
            if field_name in self.fields:
                data[field_name] = converted[field_name]
        profile = create_content(IProfile, **data)

        profiles[username] = profile
        workflow = get_workflow(IProfile, 'security')
        if workflow is not None:
            workflow.initialize(profile)
        try:
            handle_photo_upload(profile, converted)
        except Invalid, e:
            raise ValidationError(**e.error_dict)

        self.send_mail(username, profile)
        url = self.get_redirect_url()

        # delete it
        del context.__parent__[context.__name__]

        self.filestore.clear()
        return HTTPFound(headers=remember_headers, location=url)