class MultiCheckboxField(SelectMultipleField):
     '''
     This creates checkboxes
     '''
     widget = widgets.ListWidget(prefix_label=False)
     option_widget = widgets.CheckboxInput()
Beispiel #2
0
class FieldList(Field):
    """
    Encapsulate an ordered list of multiple instances of the same field type,
    keeping data as a list.

    >>> authors = FieldList(TextField('Name', [validators.required()]))

    :param unbound_field:
        A partially-instantiated field definition, just like that would be
        defined on a form directly.
    :param min_entries:
        if provided, always have at least this many entries on the field,
        creating blank ones if the provided input does not specify a sufficient
        amount.
    :param max_entries:
        accept no more than this many entries as input, even if more exist in
        formdata.
    """
    widget = widgets.ListWidget()

    def __init__(self,
                 unbound_field,
                 label=None,
                 validators=None,
                 min_entries=0,
                 max_entries=None,
                 default=tuple(),
                 **kwargs):
        super(FieldList, self).__init__(label,
                                        validators,
                                        default=default,
                                        **kwargs)
        if self.filters:
            raise TypeError(
                'FieldList does not accept any filters. Instead, define them on the enclosed field.'
            )
        if validators:
            raise TypeError(
                'FieldList does not accept any validators. Instead, define them on the enclosed field.'
            )
        assert isinstance(
            unbound_field,
            UnboundField), 'Field must be unbound, not a field class'
        self.unbound_field = unbound_field
        self.min_entries = min_entries
        self.max_entries = max_entries
        self.last_index = -1
        self._prefix = kwargs.get('_prefix', '')

    def process(self, formdata, data=_unset_value):
        self.entries = []
        if data is _unset_value or not data:
            try:
                data = self.default()
            except TypeError:
                data = self.default

        if formdata:
            indices = sorted(set(self._extract_indices(self.name, formdata)))
            if self.max_entries:
                indices = indices[:self.max_entries]

            idata = iter(data)
            for index in indices:
                try:
                    obj_data = idata.next()
                except StopIteration:
                    obj_data = _unset_value
                self._add_entry(formdata, obj_data, index=index)
        else:
            for obj_data in data:
                self._add_entry(formdata, obj_data)

        while len(self.entries) < self.min_entries:
            self._add_entry(formdata)

    def _extract_indices(self, prefix, formdata):
        """
        Yield indices of any keys with given prefix.

        formdata must be an object which will produce keys when iterated.  For
        example, if field 'foo' contains keys 'foo-0-bar', 'foo-1-baz', then
        the numbers 0 and 1 will be yielded, but not neccesarily in order.
        """
        offset = len(prefix) + 1
        for k in formdata:
            if k.startswith(prefix):
                k = k[offset:].split('-', 1)[0]
                if k.isdigit():
                    yield int(k)

    def validate(self, form, extra_validators=tuple()):
        self.errors = []
        success = True
        for subfield in self.entries:
            if not subfield.validate(form):
                success = False
                self.errors.append(subfield.errors)
        return success

    def populate_obj(self, obj, name):
        values = getattr(obj, name, None)
        try:
            ivalues = iter(values)
        except TypeError:
            ivalues = iter([])

        candidates = itertools.chain(ivalues, itertools.repeat(None))
        _fake = type('_fake', (object, ), {})
        output = []
        for field, data in itertools.izip(self.entries, candidates):
            fake_obj = _fake()
            fake_obj.data = data
            field.populate_obj(fake_obj, 'data')
            output.append(fake_obj.data)

        setattr(obj, name, output)

    def _add_entry(self, formdata=None, data=_unset_value, index=None):
        assert not self.max_entries or len(self.entries) < self.max_entries, \
            'You cannot have more than max_entries entries in this FieldList'
        new_index = self.last_index = index or (self.last_index + 1)
        name = '%s-%d' % (self.short_name, new_index)
        id = '%s-%d' % (self.id, new_index)
        field = self.unbound_field.bind(form=None,
                                        name=name,
                                        prefix=self._prefix,
                                        id=id)
        field.process(formdata, data)
        self.entries.append(field)
        return field

    def append_entry(self, data=_unset_value):
        """
        Create a new entry with optional default data.

        Entries added in this way will *not* receive formdata however, and can
        only receive object data.
        """
        return self._add_entry(data=data)

    def pop_entry(self):
        """ Removes the last entry from the list and returns it. """
        entry = self.entries.pop()
        self.last_index -= 1
        return entry

    def __iter__(self):
        return iter(self.entries)

    def __len__(self):
        return len(self.entries)

    def __getitem__(self, index):
        return self.entries[index]

    @property
    def data(self):
        return [f.data for f in self.entries]
Beispiel #3
0
class ExporterMultipleCheckBoxForm(wtforms.SelectMultipleField):
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
Beispiel #4
0
class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    password2 = PasswordField('Repeat Password', validators=[DataRequired(), EqualTo('password')])
    data = [('Black Student Union','Black Student Union'), ('Ultimate Frisbee','Ultimate Frisbee'), ('Creative Arts Club','Creative Arts Club'), ('SDT Sorority','SDT Sorority')]
    orgs = SelectMultipleField('Select organizations', choices=data, option_widget=widgets.CheckboxInput(), widget=widgets.ListWidget(prefix_label=False))
    submit = SubmitField('Register')

    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user is not None:
            raise ValidationError('Please use a different username.')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is not None:
            raise ValidationError('Please use a different email address.')
Beispiel #5
0
class PlayerListField(QuerySelectMultipleField):
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
Beispiel #6
0
def generate_submission_edit_form_class(form):
    form_fields = {}
    STATUS_CHOICES = (
        ('', _('Unmarked')),
        ('confirmed', _('Confirmed')),
        ('rejected', _('Rejected')),
        ('citizen', _('Citizen Report')),
    )

    # form_fields['contributor'] = CustomModelSelectField(
    #     _('Participant'),
    #     allow_blank=True,
    #     blank_text=_('Participant'),
    #     widget=widgets.HiddenInput(),
    #     validators=[validators.optional()],
    #     model=Participant,
    #     queryset=participants.find()
    #     )

    # form_fields['location'] = CustomModelSelectField(
    #     _('Location'),
    #     allow_blank=True,
    #     blank_text=_('Location'),
    #     widget=widgets.HiddenInput(),
    #     model=Location,
    #     queryset=locations.find()
    #     )

    for index, group in enumerate(form.groups):
        for field in group.fields:
            if field.is_comment_field:
                form_fields[field.name] = StringField(
                    field.name,
                    description=field.description,
                    widget=widgets.TextArea())
            elif field.options:
                choices = [(v, k) for k, v in field.options.items()]

                if field.allows_multiple_values:
                    form_fields[field.name] = SelectMultipleField(
                        field.name,
                        choices=choices,
                        coerce=int,
                        description=field.description,
                        filters=[lambda data: data if data else None],
                        validators=[validators.optional()],
                        option_widget=widgets.CheckboxInput(),
                        widget=widgets.ListWidget()
                    )
                else:
                    form_fields[field.name] = IntegerField(
                        field.name,
                        description=field.description,
                        validators=[
                            validators.optional(),
                            validators.AnyOf([v for v, k in choices])],
                        widget=widgets.TextInput()
                    )
            else:
                if form.form_type == 'CHECKLIST' or not field.represents_boolean:  # noqa
                    form_fields[field.name] = IntegerField(
                        field.name,
                        description=field.description,
                        validators=[
                            validators.optional(),
                            validators.NumberRange(min=field.min_value,
                                                   max=field.max_value)]
                    )
                else:
                    form_fields[field.name] = BooleanField(
                        field.name,
                        description=field.description,
                        filters=[lambda data: 1 if data else None],
                        validators=[validators.optional()]
                    )

    if (
        form.form_type == 'CHECKLIST' and
        permissions.edit_submission_quarantine_status.can()
    ):
        form_fields['quarantine_status'] = SelectField(
            choices=Submission.QUARANTINE_STATUSES,
            filters=[lambda data: data if data else ''],
            validators=[validators.optional()]
            )

    if (
        form.form_type == 'CHECKLIST' and
        permissions.edit_submission_verification_status.can()
    ):
        form_fields['verification_status'] = SelectField(
            choices=Submission.VERIFICATION_STATUSES,
            filters=[lambda data: data if data else ''],
            validators=[validators.optional()]
            )

    if form.form_type == 'INCIDENT':
        form_fields['status'] = SelectField(
            choices=STATUS_CHOICES,
            filters=[lambda data: data if data else None],
            validators=[validators.optional()]
        )
        form_fields['description'] = StringField(
            widget=widgets.TextArea()
        )
        form_fields['validate'] = validate_location

    return type(
        'SubmissionEditForm',
        (WTSecureForm,),
        form_fields
    )
Beispiel #7
0
class RegisterForm(Form):
    name = simple.StringField(label='用户名',
                              validators=[validators.DataRequired()],
                              widget=widgets.TextInput(),
                              render_kw={'class': 'form-control'},
                              default='alex')

    pwd = simple.PasswordField(
        label='密码',
        validators=[validators.DataRequired(message='密码不能为空.')],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'})

    pwd_confirm = simple.PasswordField(
        label='重复密码',
        validators=[
            validators.DataRequired(message='重复密码不能为空.'),
            validators.EqualTo('pwd', message="两次密码输入不一致")
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'})

    email = html5.EmailField(label='邮箱',
                             validators=[
                                 validators.DataRequired(message='邮箱不能为空.'),
                                 validators.Email(message='邮箱格式错误')
                             ],
                             widget=widgets.TextInput(input_type='email'),
                             render_kw={'class': 'form-control'})

    gender = core.RadioField(
        label='性别',
        choices=(
            (1, '男'),
            (2, '女'),
        ),
        coerce=int  # “1” “2”
    )
    city = core.SelectField(label='城市', choices=(
        ('bj', '北京'),
        ('sh', '上海'),
    ))

    hobby = core.SelectMultipleField(label='爱好',
                                     choices=(
                                         (1, '篮球'),
                                         (2, '足球'),
                                     ),
                                     coerce=int)

    favor = core.SelectMultipleField(
        label='喜好',
        choices=(
            (1, '篮球'),
            (2, '足球'),
        ),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        default=[1, 2])

    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.favor.choices = ((1, '篮球'), (2, '足球'), (3, '羽毛球'))

    def validate_pwd_confirm(self, field):
        """
        自定义pwd_confirm字段规则,例:与pwd字段是否一致
        :param field:
        :return:
        """
        # 最开始初始化时,self.data中已经有所有的值

        if field.data != self.data['pwd']:
            # raise validators.ValidationError("密码不一致") # 继续后续验证
            raise validators.StopValidation("密码不一致")  # 不再继续后续验证
Beispiel #8
0
class MultiCheckboxField(SelectMultipleField):
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
    params = widgets.html_params(style="width: 10px;")
Beispiel #9
0
class RegisterForm(Form):
    name = simple.StringField(
        label='用户名',
        validators=[validators.DataRequired(message="用户名不能为空")],
        widget=widgets.TextInput(),
        render_kw={'class': 'form-control'},
        default='alex')

    pwd = simple.PasswordField(
        label='密码',
        validators=[validators.DataRequired(message='密码不能为空.')],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'})

    pwd_confirm = simple.PasswordField(
        label='重复密码',
        validators=[
            validators.DataRequired(message='重复密码不能为空.'),
            validators.EqualTo('pwd', message="两次密码输入不一致")  # 校验密码一致
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'})

    email = html5.EmailField(label='邮箱',
                             validators=[
                                 validators.DataRequired(message='邮箱不能为空.'),
                                 validators.Email(message='邮箱格式错误')
                             ],
                             widget=widgets.TextInput(input_type='email'),
                             render_kw={'class': 'form-control'})

    gender = core.RadioField(
        label='性别',
        choices=(
            (1, '男'),
            (2, '女'),
        ),
        coerce=int  # int("1") 前端提交数据默认为字符串类型,coerce设置后端接收到后为int.
    )
    city = core.SelectField(label='城市', choices=(
        ('bj', '北京'),
        ('sh', '上海'),
    ))

    hobby = core.SelectMultipleField(label='爱好',
                                     choices=(
                                         (1, '篮球'),
                                         (2, '足球'),
                                     ),
                                     coerce=int)

    favor = core.SelectMultipleField(
        label='喜好',
        choices=(
            (1, '篮球'),
            (2, '足球'),
        ),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        default=[
            1,
        ])
Beispiel #10
0
class MultiCheckboxField(SelectMultipleField):
    """ Enables use of multiple checkboxes for forms """
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
Beispiel #11
0
def add_fields(form: Any, class_: str, code: Union[str, None],
               entity: Union[Entity, Link, ReferenceSystem, Type,
                             None], origin: Union[Entity, Type, None]) -> None:
    if class_ == 'actor_actor_relation':
        setattr(form, 'inverse', BooleanField(_('inverse')))
        if not entity:
            setattr(form, 'actor',
                    TableMultiField(_('actor'), [InputRequired()]))
            setattr(form, 'relation_origin_id', HiddenField())
    elif class_ == 'artifact':
        setattr(form, 'actor', TableField(_('owned by')))
    elif class_ in view_class_mapping['event']:
        setattr(form, 'event_id', HiddenField())
        setattr(form, 'event', TableField(_('sub event of')))
        setattr(form, 'event_preceding', TableField(_('preceding event')))
        if class_ in ['activity', 'acquisition', 'production']:
            setattr(form, 'place', TableField(_('location')))
        if class_ == 'acquisition':
            setattr(form, 'given_place', TableMultiField(_('given place')))
        elif class_ == 'move':
            setattr(form, 'place_from', TableField(_('from')))
            setattr(form, 'place_to', TableField(_('to')))
            setattr(form, 'artifact', TableMultiField())
            setattr(form, 'person', TableMultiField())
        elif class_ == 'production':
            setattr(form, 'artifact', TableMultiField())
    elif class_ == 'file' and not entity:
        setattr(form, 'file', MultipleFileField(_('file'), [InputRequired()]))
        if origin and origin.class_.view == 'reference':
            setattr(form, 'page', StringField())
    elif class_ == 'group':
        setattr(form, 'residence', TableField(_('residence')))
        setattr(form, 'begins_in', TableField(_('begins in')))
        setattr(form, 'ends_in', TableField(_('ends in')))
    elif class_ == 'hierarchy':
        if code == 'custom' or (entity and isinstance(entity, Type)
                                and entity.category != 'value'):
            setattr(
                form, 'multiple',
                BooleanField(_('multiple'),
                             description=_('tooltip hierarchy multiple')))
        setattr(
            form, 'classes',
            SelectMultipleField(_('classes'),
                                render_kw={'disabled': True},
                                description=_('tooltip hierarchy forms'),
                                choices=[],
                                option_widget=widgets.CheckboxInput(),
                                widget=widgets.ListWidget(prefix_label=False)))
    elif class_ == 'involvement':
        if not entity and origin:
            involved_with = 'actor' \
                if origin.class_.view == 'event' else 'event'
            setattr(form, involved_with,
                    TableMultiField(_(involved_with), [InputRequired()]))
        setattr(form, 'activity', SelectField(_('activity')))
    elif class_ == 'actor_function' and not entity:
        setattr(form, 'member_origin_id', HiddenField())
        setattr(form, 'actor' if code == 'member' else 'group',
                TableMultiField(_('actor'), [InputRequired()]))
    elif class_ in g.view_class_mapping['type']:
        setattr(form, 'is_type_form', HiddenField())
        type_ = entity if entity else origin
        if isinstance(type_, Type):
            root = g.types[type_.root[0]] if type_.root else type_
            setattr(form, str(root.id), TreeField(str(root.id)))
            if root.directional:
                setattr(form, 'name_inverse', StringField(_('inverse')))
    elif class_ == 'person':
        setattr(form, 'residence', TableField(_('residence')))
        setattr(form, 'begins_in', TableField(_('born in')))
        setattr(form, 'ends_in', TableField(_('died in')))
    elif class_ == 'reference_system':
        setattr(form, 'website_url',
                StringField(_('website URL'),
                            [OptionalValidator(), URL()]))
        setattr(form, 'resolver_url',
                StringField(_('resolver URL'),
                            [OptionalValidator(), URL()]))
        setattr(form, 'placeholder', StringField(_('example ID')))
        precision_id = str(Type.get_hierarchy('External reference match').id)
        setattr(form, precision_id, TreeField(precision_id))
        if choices := ReferenceSystem.get_class_choices(
                entity):  # type: ignore
            setattr(
                form, 'classes',
                SelectMultipleField(
                    _('classes'),
                    render_kw={'disabled': True},
                    choices=choices,
                    option_widget=widgets.CheckboxInput(),
                    widget=widgets.ListWidget(prefix_label=False)))
Beispiel #12
0
class MultiCheckboxField(SelectMultipleField):
    """Base for creating checkbox fields with multiple answers applicable"""
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
Beispiel #13
0
class BookmeetingForm(FlaskForm):
    title=StringField('Meeting title',validators=[DataRequired()])
    rooms=SelectField('Choose room',coerce=int,choices=RoomChoiceIterable())
    date=DateField('Choose date', format="%m/%d/%Y",validators=[DataRequired()])
    startTime=SelectField('Choose starting time(in 24hr expression)',coerce=int,choices=[(i,i) for i in range(9,19)])
    duration=SelectField('Choose duration of the meeting(in hours)',coerce=int,choices=[(i,i) for i in range(1,6)])
    participants_user=SelectMultipleField('Choose participants from company',coerce=int,choices=UserChoiceIterable(),option_widget=widgets.CheckboxInput(),widget=widgets.ListWidget(prefix_label=False),validators=[DataRequired()])
    participants_partner=SelectMultipleField('Choose participants from partners',coerce=int,choices=PartnerChoiceIterable(),option_widget=widgets.CheckboxInput(),widget=widgets.ListWidget(prefix_label=False))
    submit=SubmitField('Book')

    def validate_title(self,title):
        meeting=Meeting.query.filter_by(title=self.title.data).first()
        if meeting is not None: # username exist
            raise ValidationError('Please use another meeting title.')

    def validate_date(self,date):
        if self.date.data<datetime.datetime.now().date():
            raise ValidationError('You can only book for day after today.')
Beispiel #14
0
class TherapistRegistrationForm(Form):
    global stateChoices
    global countryChoices
    global treatmentMethodsList
    name             = StringField('Name', validators=[DataRequired()])
    email            = StringField('Email', validators=[DataRequired()])
    password         = PasswordField('Password', [InputRequired(), EqualTo('confirmPassword', message='Passwords must match')])
    confirmPassword  = PasswordField('Confirm Password')
    nameOfPractice   = StringField('Name Of Practice', validators=[DataRequired()])
    treatmentMethods = SelectMultipleField('Treatment Methods', choices=treatmentMethodsList, option_widget=widgets.CheckboxInput(), widget=widgets.ListWidget(prefix_label=False))
    address          = StringField('Address', validators=[DataRequired()])
    city             = StringField('City', validators=[DataRequired()])
    state            = SelectField('State', choices=stateChoices, validators=[DataRequired()])
    country          = SelectField('Country', choices=countryChoices, validators=[DataRequired()])
Beispiel #15
0
from functools import partial

from wtforms import BooleanField, validators, HiddenField, widgets, StringField, DateField, TextAreaField
from wtforms import SelectField as SelectFieldW
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms_alchemy import ModelFieldList

from dexter.forms import ModelForm, FormField, MultiCheckboxField, IntegerField, SelectField, RadioField, YesNoField, FloatField
from dexter.models import *  # noqa

QueryRadioField = partial(QuerySelectField,
                          widget=widgets.ListWidget(prefix_label=False),
                          option_widget=widgets.RadioInput())


class DocumentSourceForm(ModelForm):
    """ Form for editing a document source. """
    class Meta:
        model = DocumentSource
        only = ['name', 'quoted', 'photographed']
        field_args = {'name': {'label': 'Name'}}

    id = HiddenField('id', [validators.Optional()])
    deleted = HiddenField('deleted', default='0')
    person_id = IntegerField('person_id', widget=widgets.HiddenInput())

    named = BooleanField('The source is named', default=True)
    source_type = RadioField(
        'Type',
        default='person',
        choices=[['person', 'Adult'], ['child', 'Child'],
Beispiel #16
0
class MultiCheckboxField(SelectMultipleField):
    """Required for rendering checkbox!"""
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
Beispiel #17
0
class PipelineForm(Form):
    select_op = SelectField('Apply Operation',coerce=int,choices=lst)
    submit = SubmitField('Submit')
    lsit = widgets.ListWidget()
Beispiel #18
0
def checkbox_field(label, values, validators=None):
    return SelectMultipleField(label,
                               choices=[(v, v) for v in values],
                               option_widget=widgets.CheckboxInput(),
                               widget=widgets.ListWidget(prefix_label=False),
                               validators=validators or [])
Beispiel #19
0
class ExampleForm(Form):
    example = SelectMultipleField(
        'Pick Things!',
        choices=data,
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))
Beispiel #20
0
class MultiCheckboxField(SelectMultipleField):
    """Subclassing my own form field type."""
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
Beispiel #21
0
class HrApplicationForm(Form):

    characters = SelectMultipleField(
        label="Characters which are applying",
        validators=[DataRequired()],
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))

    alt_application = BooleanField(
        label=
        "Is this an application for an alt?, leave unchecked if you're not sure"
    )

    thesis = TextAreaField(
        "KarmaFleet is a new player corporation. If you started playing EVE more than 6 months ago, why are you looking to join a new player corporation? If you are new, what made you want to play EVE in the first place?",
        validators=[
            RequiredIfNot('alt_application'),
            Length(min=-1, max=2000, message='Max length %(max)d')
        ])
    how_long = TextAreaField("How long have you been playing EVE?",
                             validators=[
                                 RequiredIfNot('alt_application'),
                                 Length(min=-1,
                                        max=2000,
                                        message='Max length %(max)d')
                             ])
    notable_accomplishments = TextAreaField(
        "Any notable accomplishments in that time?",
        validators=[
            RequiredIfNot('alt_application'),
            Length(min=-1, max=2000, message='Max length %(max)d')
        ])
    corporation_history = TextAreaField(
        "Walk us through your Corporation history:",
        validators=[
            RequiredIfNot('alt_application'),
            Length(min=-1, max=2000, message='Max length %(max)d')
        ])
    why_leaving = TextAreaField(
        "Why are you leaving your current Corporation?",
        validators=[
            RequiredIfNot('alt_application'),
            Length(min=-1, max=2000, message='Max length %(max)d')
        ])
    what_know = TextAreaField("What do you know about KarmaFleet",
                              validators=[
                                  RequiredIfNot('alt_application'),
                                  Length(min=-1,
                                         max=2000,
                                         message='Max length %(max)d')
                              ])
    what_expect = TextAreaField(
        "How do you expect daily life in KarmaFleet to be?",
        validators=[
            RequiredIfNot('alt_application'),
            Length(min=-1, max=2000, message='Max length %(max)d')
        ])
    bought_characters = TextAreaField(
        "Do you have any other accounts or characters? Are any of your characters bought, and if so, which ones?",
        validators=[
            RequiredIfNot('alt_application'),
            Length(min=-1, max=2000, message='Max length %(max)d')
        ])
    why_interested = TextAreaField(
        "Why are you interested in joining KarmaFleet?",
        validators=[
            RequiredIfNot('alt_application'),
            Length(min=-1, max=2000, message='Max length %(max)d')
        ])
    goon_interaction = TextAreaField(
        "Have you ever interacted with another member of Goonswarm Federation?",
        validators=[
            RequiredIfNot('alt_application'),
            Length(min=-1, max=2000, message='Max length %(max)d')
        ])
    friends = TextAreaField(
        "Do you have any friends in KarmaFleet? If so, who?",
        validators=[
            RequiredIfNot('alt_application'),
            Length(min=-1, max=2000, message='Max length %(max)d')
        ])

    scale = SelectField(
        "On a scale from 1 to 10, where 1 is pure PvE and 10 is pure PvP, where do you see yourself?",
        choices=[('0 (Not Sure)', '0 (Not Sure)'),
                 ('1 (Pure PVE)', '1 (Pure PVE)'), ('2', '2'), ('3', '3'),
                 ('4', '4'),
                 ('5 (Equal PVE and PVP)', '5 (Equal PVE and PVP)'),
                 ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'),
                 ('10 (Pure PVP)', '10 (Pure PVP)')])

    favorite_role = TextAreaField("What's your favorite role to play, why?",
                                  validators=[
                                      RequiredIfNot('alt_application'),
                                      Length(min=-1,
                                             max=2000,
                                             message='Max length %(max)d')
                                  ])
    find_out = TextAreaField("How did you find out about KarmaFleet?",
                             validators=[
                                 RequiredIfNot('alt_application'),
                                 Length(min=-1,
                                        max=2000,
                                        message='Max length %(max)d')
                             ])

    recaptcha = RecaptchaField()

    submit = SubmitField(label='Submit Application')
Beispiel #22
0
class FieldList(Field):
    """
    Encapsulate an ordered list of multiple instances of the same field type,
    keeping data as a list.

    >>> authors = FieldList(StringField('Name', [validators.DataRequired()]))

    :param unbound_field:
        A partially-instantiated field definition, just like that would be
        defined on a form directly.
    :param min_entries:
        if provided, always have at least this many entries on the field,
        creating blank ones if the provided input does not specify a sufficient
        amount.
    :param max_entries:
        accept no more than this many entries as input, even if more exist in
        formdata.
    """

    widget = widgets.ListWidget()

    def __init__(self,
                 unbound_field,
                 label=None,
                 validators=None,
                 min_entries=0,
                 max_entries=None,
                 default=(),
                 **kwargs):
        super(FieldList, self).__init__(label,
                                        validators,
                                        default=default,
                                        **kwargs)
        if self.filters:
            raise TypeError(
                "FieldList does not accept any filters. Instead, define"
                " them on the enclosed field.")
        assert isinstance(
            unbound_field,
            UnboundField), "Field must be unbound, not a field class"
        self.unbound_field = unbound_field
        self.min_entries = min_entries
        self.max_entries = max_entries
        self.last_index = -1
        self._prefix = kwargs.get("_prefix", "")

    def process(self, formdata, data=unset_value):
        self.entries = []
        if data is unset_value or not data:
            try:
                data = self.default()
            except TypeError:
                data = self.default

        self.object_data = data

        if formdata:
            indices = sorted(set(self._extract_indices(self.name, formdata)))
            if self.max_entries:
                indices = indices[:self.max_entries]

            ldata = list(data)
            for index in indices:
                if index < len(ldata):
                    obj_data = ldata[index]
                else:
                    obj_data = unset_value
                self._add_entry(formdata, obj_data, index=index)
        else:
            for obj_data in data:
                self._add_entry(formdata, obj_data)

        while len(self.entries) < self.min_entries:
            self._add_entry(formdata)

    def _extract_indices(self, prefix, formdata):
        """
        Yield indices of any keys with given prefix.

        formdata must be an object which will produce keys when iterated.  For
        example, if field 'foo' contains keys 'foo-0-bar', 'foo-1-baz', then
        the numbers 0 and 1 will be yielded, but not neccesarily in order.
        """
        offset = len(prefix) + 1
        for k in formdata:
            if k.startswith(prefix):
                k = k[offset:].split("-", 1)[0]
                if k.isdigit():
                    yield int(k)

    def validate(self, form, extra_validators=()):
        """
        Validate this FieldList.

        Note that FieldList validation differs from normal field validation in
        that FieldList validates all its enclosed fields first before running any
        of its own validators.
        """
        self.errors = []

        # Run validators on all entries within
        for subfield in self.entries:
            subfield.validate(form)
            self.errors.append(subfield.errors)

        if not any(x for x in self.errors):
            self.errors = []

        chain = itertools.chain(self.validators, extra_validators)
        self._run_validation_chain(form, chain)

        return len(self.errors) == 0

    def populate_obj(self, obj, name):
        values = getattr(obj, name, None)
        try:
            ivalues = iter(values)
        except TypeError:
            ivalues = iter([])

        candidates = itertools.chain(ivalues, itertools.repeat(None))
        _fake = type(str("_fake"), (object, ), {})
        output = []
        for field, data in izip(self.entries, candidates):
            fake_obj = _fake()
            fake_obj.data = data
            field.populate_obj(fake_obj, "data")
            output.append(fake_obj.data)

        setattr(obj, name, output)

    def _add_entry(self, formdata=None, data=unset_value, index=None):
        assert (
            not self.max_entries or len(self.entries) < self.max_entries
        ), "You cannot have more than max_entries entries in this FieldList"
        if index is None:
            index = self.last_index + 1
        self.last_index = index
        name = "%s-%d" % (self.short_name, index)
        id = "%s-%d" % (self.id, index)
        field = self.unbound_field.bind(
            form=None,
            name=name,
            prefix=self._prefix,
            id=id,
            _meta=self.meta,
            translations=self._translations,
        )
        field.process(formdata, data)
        self.entries.append(field)
        return field

    def append_entry(self, data=unset_value):
        """
        Create a new entry with optional default data.

        Entries added in this way will *not* receive formdata however, and can
        only receive object data.
        """
        return self._add_entry(data=data)

    def pop_entry(self):
        """ Removes the last entry from the list and returns it. """
        entry = self.entries.pop()
        self.last_index -= 1
        return entry

    def __iter__(self):
        return iter(self.entries)

    def __len__(self):
        return len(self.entries)

    def __getitem__(self, index):
        return self.entries[index]

    @property
    def data(self):
        return [f.data for f in self.entries]
Beispiel #23
0
class RegisterForm(Form):
    name = simple.StringField(
        label='用户名',
        validators=[
            validators.DataRequired()
        ],
        widget=widgets.TextInput(),
        render_kw={'class': 'form-control'},
        default='alex'
    )

    pwd = simple.PasswordField(
        label='密码',
        validators=[
            validators.DataRequired(message='密码不能为空.')
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'}
    )

    pwd_confirm = simple.PasswordField(
        label='重复密码',
        validators=[
            validators.DataRequired(message='重复密码不能为空.'),
            validators.EqualTo('pwd', message="两次密码输入不一致")
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'}
    )

    email = html5.EmailField(
        label='邮箱',
        validators=[
            validators.DataRequired(message='邮箱不能为空.'),
            validators.Email(message='邮箱格式错误')
        ],
        widget=widgets.TextInput(input_type='email'),
        render_kw={'class': 'form-control'}
    )

    gender = core.RadioField(
        label='性别',
        choices=(
            (1, '男'),
            (2, '女'),
        ),
        coerce=int
    )
    city = core.SelectField(
        label='城市',
        choices=SQLHelper.fetch_all('select id,name from city',{},None),
        # choices=(
        #     (1, '篮球'),
        #     (2, '足球'),
        # ),
        coerce=int
    )

    hobby = core.SelectMultipleField(
        label='爱好',
        choices=(
            (1, '篮球'),
            (2, '足球'),
        ),
        coerce=int
    )

    favor = core.SelectMultipleField(
        label='喜好',
        choices=(
            (1, '篮球'),
            (2, '足球'),
        ),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        default=[1, 2]
    )
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.city.choices = SQLHelper.fetch_all('select id,name from city',{},None)


    def validate_name(self, field):
        """
        自定义pwd_confirm字段规则,例:与pwd字段是否一致
        :param field:
        :return:
        """
        # 最开始初始化时,self.data中已经有所有的值
        # print(field.data) # 当前name传过来的值
        # print(self.data) # 当前传过来的所有的值:name,gender.....

        obj = SQLHelper.fetch_one('select id from users where name=%s',[field.data,])
        if obj:
            raise validators.ValidationError("用户名已经存在") # 继续后续验证
Beispiel #24
0
class MultiCheckboxField(SelectMultipleField):
    """
    Allow people to tick multiple checkboxes
    """
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
Beispiel #25
0
class JournalInformation(Form):
    """All the bibliographic metadata associated with a journal in the DOAJ"""

    title = StringField('Journal Title', [validators.DataRequired()])
    url = URLField('URL', [validators.DataRequired(), URLOptionalScheme()])
    alternative_title = StringField('Alternative Title',
                                    [validators.Optional()])
    pissn = StringField(
        'Journal ISSN (print version)',
        [
            OptionalIf('eissn'),
            validators.Regexp(regex=ISSN_REGEX, message=ISSN_ERROR)
        ],
        description=
        'Only provide the print ISSN if your journal has one, otherwise leave this field blank. Write the ISSN with the hyphen "-" e.g. 1234-4321.',
    )
    eissn = StringField(
        'Journal ISSN (online version)',
        [
            OptionalIf('pissn'),
            validators.Regexp(regex=ISSN_REGEX, message=ISSN_ERROR)
        ],
        description=
        'Cannot be the same as the P-ISSN. Write the EISSN with the hyphen "-" e.g. 1234-4321.',
    )
    publisher = StringField('Publisher', [validators.DataRequired()])
    society_institution = StringField(
        'Society or Institution',
        [validators.Optional()],
        description=
        'The name of the Society or Institution that the journal belongs to',
    )
    platform = StringField(
        'Platform, Host or Aggregator', [validators.Optional()],
        description=
        'The name of the platform, host or aggregator of the journal content, e.g. OJS, HighWire Press, EBSCO etc.'
    )
    contact_name = StringField(
        'Name of contact for this journal',
        [validators.DataRequired()],
        description='Somebody who DOAJ can contact about this journal',
    )
    contact_email = StringField('Contact\'s email address', [
        validators.DataRequired(),
        validators.Email(message='Invalid email address.')
    ])
    confirm_contact_email = StringField('Confirm contact\'s email address', [
        validators.DataRequired(),
        validators.Email(message='Invalid email address.'),
        validators.EqualTo('contact_email', EMAIL_CONFIRM_ERROR)
    ])
    country = SelectField(
        'In which country is the publisher of the journal based?',
        [validators.DataRequired()],
        description=
        'Select the country where the publishing company is legally registered',
        choices=Choices.country(),
    )
    processing_charges = RadioField(
        'Does the journal have article processing charges (APCs)?',
        [validators.DataRequired()],
        # description = 'If "No" proceed to question below',
        choices=Choices.processing_charges())
    processing_charges_url = URLField(
        'Enter the URL where this information can be found',
        [validators.DataRequired(),
         URLOptionalScheme()],
        # description='This field is optional if you have selected "No" above'
    )
    processing_charges_amount = IntegerField(
        'Amount',
        [
            OptionalIf('processing_charges',
                       optvals=Choices.processing_charges_amount_optional())
        ],
    )
    processing_charges_currency = SelectField(
        'Currency',
        [
            OptionalIf('processing_charges',
                       optvals=Choices.processing_charges_currency_optional())
        ],
        choices=Choices.currency(),
    )

    submission_charges = RadioField(
        'Does the journal have article submission charges?',
        [validators.DataRequired()],
        # description = 'If "No" proceed to question below',
        choices=Choices.submission_charges())
    submission_charges_url = URLField(
        'Enter the URL where this information can be found',
        [validators.DataRequired(),
         URLOptionalScheme()],
        # description='This field is optional if you have selected "No" above'
    )
    submission_charges_amount = IntegerField(
        'Amount',
        [
            OptionalIf('submission_charges',
                       optvals=Choices.submission_charges_amount_optional())
        ],
    )
    submission_charges_currency = SelectField(
        'Currency',
        [
            OptionalIf('submission_charges',
                       optvals=Choices.submission_charges_amount_optional())
        ],
        choices=Choices.currency(),
    )
    waiver_policy = RadioField(
        'Does the journal have a waiver policy (for developing country authors etc)?',
        [validators.DataRequired()],
        choices=Choices.waiver_policy())
    waiver_policy_url = URLField(
        'Enter the URL where this information can be found', [
            OptionalIf('waiver_policy',
                       optvals=Choices.waiver_policy_url_optional()),
            URLOptionalScheme()
        ])
    digital_archiving_policy = SelectMultipleField(
        'What digital archiving policy does the journal use?', [
            validators.DataRequired(),
            ExclusiveCheckbox(Choices.digital_archiving_policy_val("none")),
            ExtraFieldRequiredIf(
                'digital_archiving_policy_library',
                reqval=Choices.digital_archiving_policy_val("library")),
            ExtraFieldRequiredIf(
                'digital_archiving_policy_other',
                reqval=Choices.digital_archiving_policy_val("other")),
        ],
        description=
        "Select all that apply. Institutional archives and publishers' own online archives are not valid",
        choices=Choices.digital_archiving_policy(),
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))
    digital_archiving_policy_other = StringField('', )
    digital_archiving_policy_library = StringField('', )
    digital_archiving_policy_url = URLField(
        'Enter the URL where this information can be found',
        [
            OptionalIf(
                'digital_archiving_policy',
                optvals=Choices.digital_archiving_policy_url_optional()),
            URLOptionalScheme()
        ],
        description=
        'This field is optional if you have only selected "No policy in place" above',
    )
    crawl_permission = RadioField(
        'Does the journal allow anyone to crawl the full-text of the journal?',
        [validators.DataRequired()],
        choices=Choices.crawl_permission())
    article_identifiers = SelectMultipleField(
        'Which article identifiers does the journal use?',
        [
            validators.DataRequired(),
            ExtraFieldRequiredIf(
                'article_identifiers_other',
                reqval=Choices.article_identifiers_val("other")),
            ExclusiveCheckbox()
        ],
        choices=Choices.article_identifiers(),
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False),
    )
    article_identifiers_other = StringField('', )
    download_statistics = RadioField(
        'Does the journal provide article download statistics?',
        [validators.DataRequired()],
        description='If "No" proceed to question 32',
        choices=Choices.download_statistics())
    download_statistics_url = StringField(
        'Enter the URL where this information can be found',
        [validators.Optional()],
    )
    first_fulltext_oa_year = IntegerField(
        'What was the first calendar year in which a complete volume of the journal provided online Open Access content to the Full Text of all articles? (Full Text may be provided as PDFs. Does not apply for new journals.)',
        [
            validators.DataRequired(),
            validators.NumberRange(min=1600, max=(datetime.now().year))
        ],
        description='Use 4 digits for the year, i.e. YYYY format')
    fulltext_format = SelectMultipleField(
        'Please indicate which formats of full text are available', [
            validators.DataRequired(),
            ExtraFieldRequiredIf('fulltext_format_other',
                                 reqval=Choices.fulltext_format_val("other"))
        ],
        description='Tick all that apply',
        choices=Choices.fulltext_format(),
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))
    fulltext_format_other = StringField('', )
    keywords = TagListField(
        'Add keyword(s) that best describe the journal (comma delimited)', [
            validators.DataRequired(),
            MaxLen(6, message='You can only enter up to {max_len} keywords.')
        ],
        description='Maximum 6. Keywords must be in English.')
    languages = SelectMultipleField(
        'Select the language(s) that the Full Text of the articles is published in',
        [validators.DataRequired()],
        choices=Choices.language(),
        description="You can select multiple languages")
    editorial_board_url = URLField(
        'What is the URL for the Editorial Board page?',
        [validators.DataRequired(),
         URLOptionalScheme()],
        description=
        'The journal must have either an editor or an editorial board with at least 5 clearly identifiable members and affiliation information. We may ask for affiliation information and email addresses as part of our checks.'
    )
    review_process = SelectField(
        'Please select the review process for papers',
        [validators.DataRequired()],
        choices=Choices.review_process(),
        default=Choices.review_process_default(),
    )
    review_process_url = URLField(
        'Enter the URL where this information can be found', [
            OptionalIf('review_process',
                       optvals=Choices.review_process_url_optional()),
            URLOptionalScheme()
        ],
        description='This field is optional if you have selected "None" above.'
    )
    aims_scope_url = URLField("What is the URL for the journal's Aims & Scope",
                              [validators.DataRequired(),
                               URLOptionalScheme()])
    instructions_authors_url = URLField(
        "What is the URL for the journal's instructions for authors?",
        [validators.DataRequired(),
         URLOptionalScheme()])
    plagiarism_screening = RadioField(
        'Does the journal have a policy of screening for plagiarism?',
        [validators.DataRequired()],
        description='If "No" proceed to question 43',
        choices=Choices.plagiarism_screening())
    plagiarism_screening_url = URLField(
        "Enter the URL where this information can be found", [
            OptionalIf('plagiarism_screening',
                       optvals=Choices.plagiarism_screening_url_optional()),
            URLOptionalScheme()
        ])
    publication_time = IntegerField(
        'What is the average number of weeks between submission and publication?',
        [validators.DataRequired(),
         validators.NumberRange(min=0, max=53)])
    oa_statement_url = URLField(
        "What is the URL for the journal's Open Access statement?",
        [validators.DataRequired(),
         URLOptionalScheme()])
    license_embedded = RadioField(
        'Does the journal embed or display simple machine-readable CC licensing information in its articles?',
        [validators.DataRequired()],
        choices=Choices.licence_embedded(),
        description=
        'For more information go to <a target="_blank" href="http://wiki.creativecommons.org/CC_REL">http://wiki.creativecommons.org/CC_REL</a><br><br>If "No" proceed to question 47.',
    )
    license_embedded_url = URLField(
        "Please provide a URL to an example page with embedded licensing information",
        [
            OptionalIf('license_embedded',
                       optvals=Choices.licence_embedded_url_optional()),
            URLOptionalScheme()
        ])
    license = RadioField(
        'Does the journal allow reuse and remixing of its content, in accordance with a CC license?',
        [
            validators.DataRequired(),
            ExtraFieldRequiredIf('license_other',
                                 reqval=Choices.licence_val("other"))
        ],
        choices=Choices._licence,
        description=
        'For more information go to <a href="http://creativecommons.org/licenses/" target="_blank">http://creativecommons.org/licenses/</a>'
    )
    license_other = StringField('', )
    license_checkbox = SelectMultipleField(
        'Which of the following does the content require? (Tick all that apply.)',
        choices=Choices.licence_checkbox(),
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False),
    )
    license_url = URLField(
        "Enter the URL on your site where your license terms are stated",
        [validators.Optional(), URLOptionalScheme()])
    open_access = RadioField(
        "Does the journal allow readers to 'read, download, copy, distribute, print, search, or link to the full texts' of its articles?",
        [validators.DataRequired()],
        choices=Choices.open_access(),
        description=
        'From the <a href="http://www.budapestopenaccessinitiative.org/read" target="_blank">Budapest Open Access Initiative\'s definition of Open Access</a>',
    )
    deposit_policy = SelectMultipleField(
        'With which deposit policy directory does the journal have a registered deposit policy?',
        [
            validators.DataRequired(),
            ExtraFieldRequiredIf(
                'deposit_policy_other',
                reqval=Choices.deposit_policy_other_val("other")),
            ExclusiveCheckbox()
        ],
        description='Select all that apply.',
        choices=Choices.deposit_policy(),
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))
    deposit_policy_other = StringField('', )
    copyright = RadioField(
        'Does the journal allow the author(s) to hold the copyright without restrictions?',
        [
            validators.DataRequired(),
            ExtraFieldRequiredIf('copyright_other',
                                 reqval=Choices.copyright_other_val("other"))
        ],
        choices=Choices.copyright())
    copyright_other = StringField('', )
    copyright_url = URLField(
        'Enter the URL where this information can be found', [
            OptionalIf('copyright', optvals=Choices.copyright_url_optional()),
            URLOptionalScheme()
        ])
    publishing_rights = RadioField(
        'Will the journal allow the author(s) to retain publishing rights without restrictions?',
        [
            validators.Required(),
            ExtraFieldRequiredIf(
                'publishing_rights_other',
                reqval=Choices.publishing_rights_other_val("other"))
        ],
        choices=Choices.publishing_rights())
    publishing_rights_other = StringField('', )
    publishing_rights_url = URLField(
        'Enter the URL where this information can be found', [
            OptionalIf('publishing_rights',
                       optvals=Choices.publishing_rights_url_optional()),
            URLOptionalScheme()
        ])
Beispiel #26
0
class RadioButtonField(SelectField):
    """Radio button field"""
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.RadioInput()
Beispiel #27
0
class CheckboxMultipleField(SelectMultipleField):
    """Multiple Checkbox field"""
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
Beispiel #28
0
class MultiCheckboxField(SelectMultipleField):
    """A multiple-select, except displays a list of checkboxes"""
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
Beispiel #29
0
class MultiCheckboxField(SelectMultipleField):
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
Beispiel #30
0
class MultiCheckBox(SelectMultipleField):
    """Creates checkbox widget, used by CreateForm"""

    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()