Esempio n. 1
0
class LocationMixin:
    name = StringField(lazy_gettext('Name'), validators=[Length(max=128)])
    lonlat = StringField(lazy_gettext('Position'),
                         validators=[Length(max=256), lonlat_check])
    descr = TextAreaField(lazy_gettext('Notes'))
    bortle = FloatField(lazy_gettext('Bortle'),
                        validators=[NumberRange(min=0.0, max=9.0)])
    rating = IntegerField(lazy_gettext('Rating'),
                          default=5,
                          validators=[NumberRange(min=0, max=10)])
    is_for_observation = BooleanField(
        lazy_gettext('Is suitable for observation'), default=True)
    is_public = BooleanField(lazy_gettext('Is public'), default=True)
    country_code = StringField(lazy_gettext('Country'),
                               validators=[
                                   InputRequired(),
                               ])
    time_zone = SelectField(lazy_gettext('Time Zone'),
                            choices=pytz.all_timezones,
                            validators=[Optional()])
    iau_code = IntegerField(lazy_gettext('IAU code'), validators=[Optional()])
Esempio n. 2
0
 class SubmissionForm(Form):
     attribution_name = StringField(
         'Your Name (for future attribution purposes)', [
             validators.InputRequired(),
             validators.Length(min=3,
                               max=50,
                               message="Srsly, give us a decent username "
                               "(%(min)d - %(max)d chars),"
                               " doesn't even have to be real.")
         ])
     excuse = TextAreaField('What\'s YOUR excuse !?!?', [
         validators.Length(min=5,
                           max=140,
                           message="Please provide %(min)d - %(max)d "
                           "characters"),
     ])
     nocaptcha = NoCaptchaField(
         public_key=settings.RECAPTCHA_SITE_KEY,
         private_key=settings.RECAPTCHA_SECRET_KEY,
         secure=True,
     )
Esempio n. 3
0
class EstimationForm(FlaskForm):
    speed = IntegerField(
        label=_('Speed'),
        description=_(
            'Reading speed. Usually this value is about 200 words per minute.'
        ),
        default=200,
        validators=[DataRequired()])
    url = URLField(
        label='URL',
        description=_(
            'Paste the URL of the website that should be estimated. Max length'
            ' is 2083 characters.'),
        validators=[Length(max=2083), URL()])
    text = TextAreaField(
        label=_('Plain text'),
        description=_(
            'Plain text for reading estimation. Max length is 500 000'
            ' characters.'),
        validators=[Length(max=500000)])
    recaptcha = RecaptchaField()
Esempio n. 4
0
class CommentForm(FlaskForm):
    """
    评论表单
    """
    content = TextAreaField(
        label="内容",
        validators=[
            DataRequired("请输入内容!"),
        ],
        description="内容",
        render_kw={
            "id": "input_content"
        }
    )
    submit = SubmitField(
        label='提交评论',
        render_kw={
            "class": "btn btn-success",
            "id": "btn-sub"
        }
    )
Esempio n. 5
0
class ConductReportForm(FlaskForm):
    """Information required for a code of conduct report."""

    ANONYMOUS_CHOICES = (
        (1, "I wish to remain anonymous."),
        (
            0,
            " ".join((
                "Share my identity with the code of conduct team.",
                "It will not be shared with anyone else.",
            )),
        ),
    )

    talk_id = IntegerField(widget=HiddenInput())
    text = TextAreaField(
        "Please describe why this talk may violate the code of conduct.",
        validators=[InputRequired()],
    )
    anonymous = RadioField(choices=ANONYMOUS_CHOICES,
                           coerce=lambda data: bool(int(data)))
Esempio n. 6
0
class InvitationForm(IndicoForm):
    from_address = SelectField(_('From'), [DataRequired()])
    subject = StringField(_('Subject'), [DataRequired()])
    body = TextAreaField(_('Email body'), [DataRequired()], widget=CKEditorWidget(simple=True))
    recipients = EmailListField(_('Recipients'), [DataRequired()], description=_('One email address per line.'))
    copy_for_sender = BooleanField(_('Send copy to me'), widget=SwitchWidget())
    submitted = HiddenField()

    def __init__(self, *args, **kwargs):
        event = kwargs.pop('event')
        super().__init__(*args, **kwargs)
        self.from_address.choices = list(event.get_allowed_sender_emails().items())
        self.body.description = render_placeholder_info('survey-link-email', event=None, survey=None)

    def is_submitted(self):
        return super().is_submitted() and 'submitted' in request.form

    def validate_body(self, field):
        missing = get_missing_placeholders('survey-link-email', field.data, event=None, survey=None)
        if missing:
            raise ValidationError(_('Missing placeholders: {}').format(', '.join(missing)))
Esempio n. 7
0
class DagRunEditForm(DagRunForm):
    """Form for editing DAG Run"""

    dag_id = StringField(lazy_gettext('Dag Id'),
                         validators=[InputRequired()],
                         widget=BS3TextFieldROWidget())
    start_date = DateTimeWithTimezoneField(
        lazy_gettext('Start Date'), widget=AirflowDateTimePickerROWidget())
    end_date = DateTimeWithTimezoneField(
        lazy_gettext('End Date'), widget=AirflowDateTimePickerROWidget())
    run_id = StringField(lazy_gettext('Run Id'),
                         validators=[InputRequired()],
                         widget=BS3TextFieldROWidget())
    execution_date = DateTimeWithTimezoneField(
        lazy_gettext('Execution Date'),
        widget=AirflowDateTimePickerROWidget(),
        validators=[InputRequired()],
    )
    conf = TextAreaField(lazy_gettext('Conf'),
                         validators=[ValidJson(), Optional()],
                         widget=BS3TextAreaROWidget())
Esempio n. 8
0
class CreateAccountForm(FlaskForm):
    username = StringField("Username", validators=[DataRequired()])
    password = PasswordField("Password", validators=[DataRequired()])
    password2 = PasswordField("Confirm Password",
                              validators=[DataRequired(),
                                          EqualTo("password")])
    discord_name = StringField("Discord Name", validators=[DataRequired()])
    pronunciation = StringField("How is your username pronounced?",
                                validators=[DataRequired()])
    pronouns = RadioField("What are your preferred pronouns?",
                          choices=[("he/him", "He/Him"),
                                   ("she/her", "She/Her"),
                                   ("they/them", "They/Them")],
                          validators=[DataRequired()])
    about = TextAreaField("What are some interesting facts about yourself?")
    submit = SubmitField("Create Account")

    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user is not None:
            raise ValidationError("That username is taken.")
Esempio n. 9
0
class EmailEventPersonsForm(fossirForm):
    from_address = SelectField(_('From'), [DataRequired()])
    subject = StringField(_('Subject'), [DataRequired()])
    body = TextAreaField(_('Email body'), [DataRequired()], widget=CKEditorWidget(simple=True))
    recipients = fossirEmailRecipientsField(_('Recipients'))
    copy_for_sender = BooleanField(_('Send copy to me'), widget=SwitchWidget(),
                                   description=_('Send copy of each email to my mailbox'))
    person_id = HiddenFieldList()
    user_id = HiddenFieldList()
    submitted = HiddenField()

    def __init__(self, *args, **kwargs):
        register_link = kwargs.pop('register_link')
        event = kwargs.pop('event')
        super(EmailEventPersonsForm, self).__init__(*args, **kwargs)
        self.from_address.choices = event.get_allowed_sender_emails().items()
        self.body.description = render_placeholder_info('event-persons-email', event=None, person=None,
                                                        register_link=register_link)

    def is_submitted(self):
        return super(EmailEventPersonsForm, self).is_submitted() and 'submitted' in request.form
Esempio n. 10
0
class AbstractCommentForm(IndicoForm):
    text = TextAreaField(_("Comment"), [DataRequired()],
                         render_kw={
                             'placeholder': _("Leave a comment..."),
                             'class': 'grow'
                         })
    visibility = IndicoEnumSelectField(_("Visibility"), [DataRequired()],
                                       enum=AbstractCommentVisibility,
                                       skip={AbstractCommentVisibility.users})

    def __init__(self, *args, **kwargs):
        comment = kwargs.get('obj')
        user = comment.user if comment else kwargs.pop('user')
        abstract = kwargs.pop('abstract')
        super().__init__(*args, **kwargs)
        if not abstract.event.cfa.allow_contributors_in_comments:
            self.visibility.skip.add(AbstractCommentVisibility.contributors)
        if not abstract.can_judge(user) and not abstract.can_convene(user):
            self.visibility.skip.add(AbstractCommentVisibility.judges)
            if not abstract.can_review(user):
                del self.visibility
Esempio n. 11
0
class ApplicationForm(IndicoForm):
    name = StringField(_("Name"), [DataRequired()])
    description = TextAreaField(_("Description"))
    redirect_uris = RedirectURIField(
        _("Allowed authorization callback URLs"), [DataRequired()],
        description=_(
            "More than one URL can be specified adding new lines. The "
            "redirect_uri sent by the OAuth client must use the same protocol "
            "and host/port. If an entry contains a path, the redirect_uri's "
            "path must start with this path."))
    default_scopes = IndicoSelectMultipleCheckboxField(
        'Allowed scopes', [DataRequired()],
        choices=sorted(SCOPES.items(), key=itemgetter(1)))
    is_enabled = BooleanField(
        _("Enabled"),
        widget=SwitchWidget(),
        description=_(
            "If an application is not enabled, its OAuth tokens cannot be used and "
            "user cannot be prompted to authorize the application."))
    is_trusted = BooleanField(
        _("Trusted"),
        widget=SwitchWidget(),
        description=
        _("Trusted applications will be granted authorization automatically and "
          "no intermediate page will be displayed during the authorization process."
          ))

    def __init__(self, *args, **kwargs):
        self.application = kwargs.pop('application', None)
        super(ApplicationForm, self).__init__(*args, **kwargs)

    def validate_name(self, field):
        query = OAuthApplication.find(name=field.data)
        if self.application:
            query = query.filter(
                db.func.lower(OAuthApplication.name) !=
                self.application.name.lower())
        if query.count():
            raise ValidationError(
                _("There is already an application with this name"))
Esempio n. 12
0
class UserdetailForm(FlaskForm):
    name = StringField(label="昵称",
                       validators=[DataRequired("请输入昵称!")],
                       description="昵称",
                       render_kw={
                           "class": "form-control",
                           "placeholder": "请输入昵称!",
                       })
    email = StringField(label="邮箱",
                        validators=[DataRequired("请输入邮箱!"),
                                    Email("邮箱格式不正确!")],
                        description="邮箱",
                        render_kw={
                            "class": "form-control",
                            "placeholder": "请输入邮箱!",
                        })
    phone = StringField(label="手机",
                        validators=[
                            DataRequired("请输入手机!"),
                            Regexp("1[3458]\d{9}", message="手机格式不正确!")
                        ],
                        description="手机",
                        render_kw={
                            "class": "form-control",
                            "placeholder": "请输入手机号!",
                        })
    face = FileField(
        label="头像",
        validators=[DataRequired("请上传头像!")],
        description="头像",
    )
    info = TextAreaField(label="简介",
                         validators=[DataRequired("请输入简介!")],
                         render_kw={
                             "class": "form-control",
                             "rows": 10
                         })
    submit = SubmitField('保存修改', render_kw={
        "class": "btn btn-success",
    })
Esempio n. 13
0
class PaperReviewForm(IndicoForm):
    """Form for reviewing a paper"""

    _order = ('proposed_action', 'comment')

    comment = TextAreaField(_("Comment"),
                            render_kw={
                                'placeholder':
                                _("You may leave a comment (only visible to "
                                  "reviewers and judges)..."),
                                'class':
                                'grow'
                            })
    proposed_action = IndicoEnumSelectField(_("Proposed Action"),
                                            [DataRequired()],
                                            enum=PaperAction)

    def __init__(self, edit=False, *args, **kwargs):
        paper = kwargs.pop('paper')
        super(PaperReviewForm, self).__init__(*args, **kwargs)
        self.event = paper.event
        if not edit:
            self.proposed_action.none = _("Propose an action...")

    @property
    def split_data(self):
        data = self.data
        return {
            'questions_data':
            {k: v
             for k, v in data.iteritems() if k.startswith('question_')},
            'review_data': {
                k: v
                for k, v in data.iteritems() if not k.startswith('question_')
            }
        }

    @property
    def has_questions(self):
        return any(x.startswith('question_') for x in self.data)
Esempio n. 14
0
class AttachmentFolderForm(IndicoForm):
    title = HiddenField(_("Name"), [DataRequired()],
                        widget=TypeaheadWidget(),
                        description=_("The name of the folder."))
    description = TextAreaField(
        _("Description"),
        description=_("Description of the folder and its content"))
    protected = BooleanField(_("Protected"), widget=SwitchWidget())
    acl = AccessControlListField(
        _("Access control list"),
        [UsedIf(lambda form, field: form.protected.data)],
        groups=True,
        allow_external=True,
        description=_(
            "The list of users and groups allowed to access the folder"))
    is_always_visible = BooleanField(
        _("Always Visible"),
        widget=SwitchWidget(),
        description=_(
            "By default, folders are always visible, even if a user cannot "
            "access them. You can disable this behavior here, hiding the folder "
            "for anyone who does not have permission to access it."))

    def __init__(self, *args, **kwargs):
        self.linked_object = kwargs.pop('linked_object')
        super(AttachmentFolderForm, self).__init__(*args, **kwargs)
        self.title.choices = self._get_title_suggestions()

    def _get_title_suggestions(self):
        query = db.session.query(AttachmentFolder.title).filter_by(
            is_deleted=False, is_default=False, object=self.linked_object)
        existing = set(x[0] for x in query)
        suggestions = set(get_default_folder_names()) - existing
        if self.title.data:
            suggestions.add(self.title.data)
        return sorted(suggestions)

    @generated_data
    def protection_mode(self):
        return ProtectionMode.protected if self.protected.data else ProtectionMode.inheriting
Esempio n. 15
0
class PluginSettingsForm(VCPluginSettingsFormBase):
    support_email = EmailField(_('Vidyo email support'))
    username = StringField(_('Username'), [DataRequired()], description=_('Indico username for Vidyo'))
    password = IndicoPasswordField(_('Password'), [DataRequired()], toggle=True,
                                   description=_('Indico password for Vidyo'))
    admin_api_wsdl = URLField(_('Admin API WSDL URL'), [DataRequired()])
    user_api_wsdl = URLField(_('User API WSDL URL'), [DataRequired()])
    indico_room_prefix = IntegerField(_('Indico tenant prefix'), [NumberRange(min=0)],
                                      description=_('The tenant prefix for Indico rooms created on this server'))
    room_group_name = StringField(_("Public rooms' group name"), [DataRequired()],
                                  description=_('Group name for public videoconference rooms created by Indico'))
    authenticators = StringField(_('Authenticators'), [DataRequired()],
                                 description=_('Identity providers to convert Indico users to Vidyo accounts'))
    num_days_old = IntegerField(_('VC room age threshold'), [NumberRange(min=1), DataRequired()],
                                description=_('Number of days after an Indico event when a videoconference room is '
                                              'considered old'))
    max_rooms_warning = IntegerField(_('Max. num. VC rooms before warning'), [NumberRange(min=1), DataRequired()],
                                     description=_('Maximum number of rooms until a warning is sent to the managers'))
    vidyo_phone_link = URLField(_('VidyoVoice phone number'),
                                description=_('Link to the list of VidyoVoice phone numbers'))
    creation_email_footer = TextAreaField(_('Creation email footer'), widget=CKEditorWidget(),
                                          description=_('Footer to append to emails sent upon creation of a VC room'))
Esempio n. 16
0
class InvitationFormBase(IndicoForm):
    _invitation_fields = ('skip_moderation',)
    _email_fields = ('email_from', 'email_subject', 'email_body')
    email_from = SelectField(_('From'), [DataRequired()])
    email_subject = StringField(_("Email subject"), [DataRequired()])
    email_body = TextAreaField(_("Email body"), [DataRequired()], widget=CKEditorWidget(simple=True))
    skip_moderation = BooleanField(_("Skip moderation"), widget=SwitchWidget(),
                                   description=_("If enabled, the user's registration will be approved automatically."))

    def __init__(self, *args, **kwargs):
        self.regform = kwargs.pop('regform')
        event = self.regform.event
        super(InvitationFormBase, self).__init__(*args, **kwargs)
        if not self.regform.moderation_enabled:
            del self.skip_moderation
        self.email_from.choices = event.get_allowed_sender_emails().items()
        self.email_body.description = render_placeholder_info('registration-invitation-email', invitation=None)

    def validate_email_body(self, field):
        missing = get_missing_placeholders('registration-invitation-email', field.data, invitation=None)
        if missing:
            raise ValidationError(_('Missing placeholders: {}').format(', '.join(missing)))
Esempio n. 17
0
class CampaignForm(FlaskForm):
    name = StringField(u'Campaign name',
                       validators=[DataRequired('Campaign name is needed')],
                       description='Name for the campaign')
    description = TextAreaField(u'Campaign description',
                                description='Description for the campaign')
    campaign_status = StringField(u'Campaign status',
                                  description='Status of the campaign')
    coverage = StringField(u'Coverage')
    start_date = DateField(u'Start date of campaign')
    end_date = DateField(u'End date of campaign', validators=[Optional()])

    campaign_managers = SelectMultipleField(u'Managers of campaign',
                                            choices=[
                                                (user, user)
                                                for user in get_osm_user()
                                            ])
    uploader = HiddenField(u'Uploader for this campaign')
    geometry = HiddenField(u'Map geometry for this campaign',
                           validators=[DataRequired('Geometry is needed')])
    selected_functions = HiddenField(u'Selected Functions')
    submit = SubmitField(u'Submit')
Esempio n. 18
0
class UserdetailForm(FlaskForm):
    name = StringField(label='账号',
                       validators=[DataRequired('请输入账号!')],
                       description='账号',
                       render_kw={
                           'class': 'form-control',
                           "placeholder": '请输入账号'
                       })
    email = StringField(label='邮箱',
                        validators=[DataRequired('请输入邮箱!'),
                                    Email('邮箱格式不正确!')],
                        description='邮箱',
                        render_kw={
                            'class': 'form-control',
                            "placeholder": '请输入邮箱'
                        })
    phone = StringField(label='手机',
                        validators=[
                            DataRequired('请输入手机!'),
                            Regexp('1[1-9]\\d{9}', message='手机格式不正确!')
                        ],
                        description='手机',
                        render_kw={
                            'class': 'form-control',
                            "placeholder": '请输入手机'
                        })
    face = FileField(
        label='头像',
        validators=[DataRequired('请上传头像!')],
        description='头像',
    )
    info = TextAreaField(label='简介',
                         validators=[DataRequired('请输入简介!')],
                         description="简介",
                         render_kw={
                             'class': 'form-control',
                             'rows': 10
                         })
    submit = SubmitField(label='保存修改', render_kw={'class': 'btn btn-success'})
Esempio n. 19
0
class ConnectionForm(DynamicForm):
    conn_id = StringField(lazy_gettext('Conn Id'), widget=BS3TextFieldWidget())
    conn_type = SelectField(lazy_gettext('Conn Type'),
                            choices=Connection._types,
                            widget=Select2Widget())
    host = StringField(lazy_gettext('Host'), widget=BS3TextFieldWidget())
    schema = StringField(lazy_gettext('Schema'), widget=BS3TextFieldWidget())
    login = StringField(lazy_gettext('Login'), widget=BS3TextFieldWidget())
    password = PasswordField(lazy_gettext('Password'),
                             widget=BS3PasswordFieldWidget())
    port = IntegerField(lazy_gettext('Port'),
                        validators=[validators.Optional()],
                        widget=BS3TextFieldWidget())
    extra = TextAreaField(lazy_gettext('Extra'),
                          widget=BS3TextAreaFieldWidget())

    # Used to customized the form, the forms elements get rendered
    # and results are stored in the extra field as json. All of these
    # need to be prefixed with extra__ and then the conn_type ___ as in
    # extra__{conn_type}__name. You can also hide form elements and rename
    # others from the connection_form.js file
    extra__jdbc__drv_path = StringField(lazy_gettext('Driver Path'),
                                        widget=BS3TextFieldWidget())
    extra__jdbc__drv_clsname = StringField(lazy_gettext('Driver Class'),
                                           widget=BS3TextFieldWidget())
    extra__google_cloud_platform__project = StringField(
        lazy_gettext('Project Id'), widget=BS3TextFieldWidget())
    extra__google_cloud_platform__key_path = StringField(
        lazy_gettext('Keyfile Path'), widget=BS3TextFieldWidget())
    extra__google_cloud_platform__keyfile_dict = PasswordField(
        lazy_gettext('Keyfile JSON'), widget=BS3PasswordFieldWidget())
    extra__google_cloud_platform__scope = StringField(
        lazy_gettext('Scopes (comma separated)'), widget=BS3TextFieldWidget())
    extra__grpc__auth_type = StringField(lazy_gettext('Grpc Auth Type'),
                                         widget=BS3TextFieldWidget())
    extra__grpc__credential_pem_file = StringField(
        lazy_gettext('Credential Keyfile Path'), widget=BS3TextFieldWidget())
    extra__grpc__scopes = StringField(lazy_gettext('Scopes (comma separated)'),
                                      widget=BS3TextFieldWidget())
Esempio n. 20
0
class UserDetailForm(FlaskForm):
    name = StringField(label="账号",
                       validators=[DataRequired("请输入账号")],
                       description="账号",
                       render_kw={
                           "class": "form-control",
                           "placeholder": "请输入账号!"
                       })
    email = StringField(
        label="邮箱",
        validators=[DataRequired("请输入邮箱"),
                    Email("邮箱格式不正确")],
        description="邮箱",
        render_kw={
            "class": "form-control",
            "placeholder": "请输入邮箱!",
            # "required": 'required'
        })
    phone = StringField(label="手机",
                        validators=[
                            DataRequired("请输入手机号"),
                            Regexp("1[3458]\d{9}", message="手机格式不正确")
                        ],
                        description="手机",
                        render_kw={
                            "class": "form-control",
                            "placeholder": "请输入手机号!"
                        })
    face = FileField(label="头像",
                     validators=[DataRequired("上传头像!")],
                     description="上传头像")
    info = TextAreaField(label="简介",
                         validators=[DataRequired("请输入简介!")],
                         description="简介",
                         render_kw={
                             "class": "form-control",
                             "row": "10!"
                         })
    submit = SubmitField('保存修改', render_kw={"class": "btn btn-success"})
Esempio n. 21
0
class EditArticleForm(FlaskForm):
    title = StringField(label=u"标题",
                        description='文章标题',
                        render_kw={
                            "class": "form-control",
                            "placeholder": "请输入文章标题"
                        })
    cate = SelectField(label=u"分类",
                       description="文章分类",
                       render_kw={"class": "form-control"})
    icon = FileField(label=u"logo",
                     description="封面",
                     render_kw={
                         "class": "form-control",
                         "placeholder": "上传封面"
                     })
    body = TextAreaField(label=u"内容",
                         description="文章内容",
                         render_kw={
                             "class": "form-control",
                             "placeholder": "请输入内容"
                         })
Esempio n. 22
0
class EmailRegistrantsForm(IndicoForm):
    from_address = SelectField(_("From"), [DataRequired()])
    cc_addresses = EmailListField(
        _("CC"),
        description=_(
            "Beware, addresses in this field will receive one mail per "
            "registrant."))
    subject = StringField(_("Subject"), [DataRequired()])
    body = TextAreaField(_("Email body"), [DataRequired()],
                         widget=CKEditorWidget(simple=True))
    recipients = IndicoEmailRecipientsField(_('Recipients'))
    copy_for_sender = BooleanField(
        _('Send copy to me'),
        widget=SwitchWidget(),
        description=_('Send copy of each email to my mailbox'))
    registration_id = HiddenFieldList()
    submitted = HiddenField()

    def __init__(self, *args, **kwargs):
        self.regform = kwargs.pop('regform')
        event = self.regform.event
        super(EmailRegistrantsForm, self).__init__(*args, **kwargs)
        self.from_address.choices = event.get_allowed_sender_emails().items()
        self.body.description = render_placeholder_info('registration-email',
                                                        regform=self.regform,
                                                        registration=None)

    def validate_body(self, field):
        missing = get_missing_placeholders('registration-email',
                                           field.data,
                                           regform=self.regform,
                                           registration=None)
        if missing:
            raise ValidationError(
                _('Missing placeholders: {}').format(', '.join(missing)))

    def is_submitted(self):
        return super(EmailRegistrantsForm,
                     self).is_submitted() and 'submitted' in request.form
Esempio n. 23
0
class ArticleForm(FlaskForm):
    title = StringField(label=u"标题",
                        description='文章标题',
                        render_kw={
                            "class": "form-control",
                            "placeholder": "请输入文章标题"
                        })
    cate = SelectField(label=u"分类",
                       description="文章分类",
                       validators=[DataRequired("请选择分类!")],
                       choices=[('0', '科技'), ('1', '搞笑'), ('2', '新闻')],
                       render_kw={"class": "form-control"})
    icon = FileField(label=u"logo",
                     description="封面",
                     render_kw={"class": "form-control-file"})
    body = TextAreaField(label=u"内容",
                         description="文章内容",
                         render_kw={
                             "id": "editor",
                             "style": "height: 300px"
                         })
    submit = SubmitField(u'发布文章', render_kw={"class": "btn btn-primary"})
Esempio n. 24
0
class CardForm(FlaskForm):
    price = FloatField('Price', validators=[DataRequired()])
    category_expenses = SelectField('Category expenses',
                                    choices=expenses,
                                    coerce=str,
                                    validators=[Optional()])
    category_incomes = SelectField('Category incomes',
                                   choices=incomes,
                                   coerce=str,
                                   validators=[Optional()])
    kind = SelectField(choices=kind_choice, coerce=int)
    day = IntegerField(validators=[NumberRange(min=1, max=31)])
    month = IntegerField(validators=[NumberRange(min=1, max=12)])
    year = IntegerField(validators=[NumberRange(min=1970)])
    note = TextAreaField(validators=[Length(max=32)])
    submit = SubmitField('Create')

    def validate_price(self, price):
        try:
            float(price.data)
        except ValidationError:
            raise ValidationError('Price must be float')
Esempio n. 25
0
class NoteForm(Form):
    title = StringField('Title')
    tags = StringField('tags')
    content = TextAreaField('Details', validators=[Required()])

    def update(self, note):
        note.entry.update(title=self.title.data, content=self.content.data)

        self.add_tags(note, self.tags.data)

    def create(self):
        note = create_log_entry('log',
                                title=self.title.data,
                                content=self.content.data)

        self.add_tags(note, self.tags.data)

        return note

    def add_tags(self, note, tags):
        for tag in self.tags.data.split(','):
            note.add_tag(tag)
Esempio n. 26
0
class RegisterForm(Form):

    username = StringField('Username', validators=[Length(min=4, max=25)])

    email = StringField('Email Address', validators=[Email()])

    password = PasswordField(
        'Password',
        [DataRequired(),
         EqualTo('confirm', message='Passwords must match')])

    confirm = PasswordField('Repeat Password')

    age = IntegerField('Age', validators=[NumberRange(min=16, max=70)])

    height = DecimalField('Height (Centimeter)', places=1)

    birthday = DateField('Birthday', format='%Y-%m-%d')

    gender = RadioField('Gender',
                        choices=[('m', 'Male'), ('f', 'Female')],
                        validators=[DataRequired()])

    job = SelectField('Job',
                      choices=[('teacher', 'Teacher'), ('doctor', 'Doctor'),
                               ('engineer', 'Engineer'), ('lawyer', 'Lawyer')])

    hobby = SelectMultipleField('Hobby',
                                choices=[('swim', 'Swimming'),
                                         ('skate', 'Skating'),
                                         ('hike', 'Hiking')])

    description = TextAreaField('Introduction of yourself')

    accept_terms = BooleanField('I accept the Terms of Use',
                                default='checked',
                                validators=[DataRequired()])

    submit = SubmitField('Register')
Esempio n. 27
0
class RegisterForm(FlaskForm):
    """Validators"""
    name = StringField("Your name ",
                       validators=[Length(min=1, max=40),
                                   DataRequired()])
    email = EmailField("Your email", validators=[Email(), DataRequired()])
    birthday = DateField("Your birthday ",
                         validators=[DataRequired()],
                         format="%Y-%m-%d")
    gender = SelectField("Select your gender",
                         validators=[DataRequired()],
                         choices=["Male", "Female"])
    password = PasswordField("Your password", validators=[DataRequired()])
    nationality = SelectField("Nationality",
                              choices=[name for name in countries])
    accept_terms = BooleanField(
        "Accepting all the terms",
        validators=[DataRequired("Please accept terms ")])
    message = TextAreaField("Your story", validators=[Length(min=-1, max=300)])
    photo = FileField("Upload your image",
                      validators=[FileAllowed(["jpeg", "jpg", "png"])])
    submit = SubmitField("Send Application ")
Esempio n. 28
0
class NewCandidateForm(Form):
    first_name = StringField('First name',
                             validators=[InputRequired(),
                                         Length(1, 64)])
    last_name = StringField('Last name',
                            validators=[InputRequired(),
                                        Length(1, 64)])
    email = EmailField('Email',
                       validators=[InputRequired(),
                                   Length(1, 64),
                                   Email()])
    phone_number = StringField('Phone Number')
    term = QuerySelectField(
        'Term',
        get_label='name',
        allow_blank=True,
        query_factory=lambda: db.session.query(Term).order_by('start_date'))
    source = StringField('Source')
    staff_contact = StringField('Staff Contact')
    notes = TextAreaField('Notes')
    demographic = FormField(DemographicForm)
    submit = SubmitField('Create')
Esempio n. 29
0
class DagRunForm(DynamicForm):
    """Form for adding DAG Run"""

    dag_id = StringField(lazy_gettext('Dag Id'),
                         validators=[InputRequired()],
                         widget=BS3TextFieldWidget())
    start_date = DateTimeWithTimezoneField(
        lazy_gettext('Start Date'), widget=AirflowDateTimePickerWidget())
    end_date = DateTimeWithTimezoneField(lazy_gettext('End Date'),
                                         widget=AirflowDateTimePickerWidget())
    run_id = StringField(lazy_gettext('Run Id'),
                         validators=[InputRequired()],
                         widget=BS3TextFieldWidget())
    state = SelectField(
        lazy_gettext('State'),
        choices=(
            ('success', 'success'),
            ('running', 'running'),
            ('failed', 'failed'),
        ),
        widget=Select2Widget(),
        validators=[InputRequired()],
    )
    execution_date = DateTimeWithTimezoneField(
        lazy_gettext('Execution Date'),
        widget=AirflowDateTimePickerWidget(),
        validators=[InputRequired()],
    )
    external_trigger = BooleanField(lazy_gettext('External Trigger'))
    conf = TextAreaField(lazy_gettext('Conf'),
                         validators=[ValidJson(), Optional()],
                         widget=BS3TextAreaFieldWidget())

    def populate_obj(self, item):
        """Populates the attributes of the passed obj with data from the form’s fields."""
        super().populate_obj(item)  # pylint: disable=no-member
        item.run_type = DagRunType.from_run_id(item.run_id)
        if item.conf:
            item.conf = json.loads(item.conf)
Esempio n. 30
0
class ImportForm(FlaskForm):
    client_id = SelectField('client_id', coerce=int, id='select_client')
    year = SelectField(validators=[DataRequired()], coerce=int, id="car-years")
    make = SelectField(validators=[DataRequired()], id="car-makes")
    model = SelectField(validators=[DataRequired()], id="car-models")
    color = SelectField(validators=[DataRequired()],
                        choices=[('black', 'Black'), ('white', 'White'),
                                 ('blue', 'Blue'), ('red', 'Red'),
                                 ('brown', 'Brown'), ('silver', 'Silver'),
                                 ('pearl', 'Pearl'), ('orange', 'Orange'),
                                 ('purple', 'Purple'), ('green', 'Green'),
                                 ('red-wine', 'Red-wine'), ('grey', 'Grey'),
                                 ('gold', 'Gold'), ('pink', 'Pink')])
    fuel = SelectField(validators=[DataRequired()],
                       choices=[('petrol', 'Petrol'), ('diesel', 'diesel')])
    transmission = SelectField(validators=[DataRequired()],
                               choices=[('automatic', 'Automatic'),
                                        ('manual', 'Manual')])
    budget = DecimalField(validators=[DataRequired()])
    engine = StringField(validators=[DataRequired()])
    special_features = TextAreaField(validators=[DataRequired()])
    submit = SubmitField('save')