Пример #1
0
class SubmitSystem(FlaskForm):
    systemname = StringField(
        'System Name',
        validators=[
            DataRequired(),
            Length(1, 64),
            Regexp(
                '^[A-Za-z][A-Za-z0-9_.]*$', 0,
                'Systemname must have only letters, numbers, dots or underscores'
            )
        ])
    site_type = SelectField(
        'Site & System type',
        choices=['GESIS (Dataset recommender)', 'LIVIVO (Document ranker)'])
    GitHubUrl = URLField('URL',
                         validators=[
                             DataRequired(message="Enter URL Please"),
                             URL(message="Enter Valid URL Please.")
                         ])

    def validate_systemname(self, field):
        if re.match('^[A-Za-z][A-Za-z0-9_.]*$', field.data):
            if System.query.filter_by(name=field.data).first():
                flash('System name already in use.', 'danger')
                raise ValidationError('System name already in use.')
        else:
            flash(
                'Systemname must have only letters, numbers, dots or underscores',
                'danger')

    submit = SubmitField('Submit')
Пример #2
0
class BookForm(FlaskForm):
    """
    Form for books
    """
    title = StringField('Titulo do livro:',
                        validators=[DataRequired('Digite o título do livro.')])

    subtitle = StringField('Subtitulo do livro(se houver):')

    authors = StringField(
        'Nome do autor(es):',
        validators=[DataRequired('Digite o nome dos autor(es)')])

    edition = IntegerField(
        'Número da edição:',
        validators=[DataRequired('Digite o número da edição')])

    location = StringField('Local de impressão:')

    publisher = StringField('Editora:')

    year = IntegerField('Ano da publicação:')

    link = URLField('Link para a revista(Se existir)')

    index = IntegerField()

    create = SubmitField('Adicionar')
Пример #3
0
class ReferenceTypeForm(IndicoForm):
    name = StringField(_("Name"), [DataRequired()],
                       description=_("The name of the external ID type"))
    url_template = URLField(
        _("URL template"),
        description=_(
            "The URL template must contain the '{value}' placeholder."))
    scheme = StringField(
        _("Scheme"),
        filters=[lambda x: x.rstrip(':') if x else x],
        description=_("The scheme/protocol of the external ID type"))

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

    def validate_name(self, field):
        query = ReferenceType.find(
            db.func.lower(ReferenceType.name) == field.data.lower())
        if self.reference_type:
            query = query.filter(ReferenceType.id != self.reference_type.id)
        if query.count():
            raise ValidationError(_("This name is already in use."))

    def validate_url_template(self, field):
        if field.data and '{value}' not in field.data:
            raise ValidationError(
                _("The URL template must contain the placeholder '{value}'."))
Пример #4
0
class EditPlacemarkForm(FlaskForm):
	id = IntegerField('Идентификатор', validators = [DataRequired(message='Идентификатор  - обязательное поле.')], id = 'editId')
	description = TextAreaField('Описание', validators = [Length(max = 128, message='Описание не должно быть длиннее 128 символов.')], id = 'editDescription')
	name = StringField('Название', validators = [DataRequired(message='Название  - обязательное поле.'), Length(max = 128, message='Название не должно быть длиннее 128 символов.')], id='editName')
	price_url = URLField('URL прайса', id='editPriceURL', validators=[Optional(), URL(message='Некорректный URL.')])
	tags = FieldList(FormField(AddTagForm))
	submit = SubmitField('Сохранить', id = 'editSubmit')
Пример #5
0
class ProfileForm(Form):
    multipart = True
    next = HiddenField()
    email = EmailField(u'Email', [Required(), Email()])
    # Don't use the same name as model because we are going to use populate_obj().
    avatar_file = FileField(u"Avatar", [Optional()])
    sex_code = RadioField(u"Sex",
                          [AnyOf([str(val) for val in SEX_TYPE.keys()])],
                          choices=[(str(val), label)
                                   for val, label in SEX_TYPE.items()])
    age = IntegerField(u'Age', [Optional(), NumberRange(AGE_MIN, AGE_MAX)])
    phone = TelField(u'Phone', [Length(max=64)])
    url = URLField(u'URL', [Optional(), URL()])
    deposit = DecimalField(
        u'Deposit',
        [Optional(), NumberRange(DEPOSIT_MIN, DEPOSIT_MAX)])
    location = TextField(u'Location', [Length(max=64)])
    bio = TextAreaField(u'Bio', [Length(max=1024)])
    submit = SubmitField(u'Save')

    def validate_name(form, field):
        user = User.get_by_id(current_user.id)
        if not user.check_name(field.data):
            raise ValidationError("Please pick another name.")

    def validate_avatar_file(form, field):
        if field.data and not allowed_file(field.data.filename):
            raise ValidationError("Please upload files with extensions: %s" %
                                  "/".join(ALLOWED_AVATAR_EXTENSIONS))
Пример #6
0
class FileForm(Form):
    name = StringField('Name', validators=[DataRequired()])
    url = URLField("Url", validators=[url()])
    category = QuerySelectField('Category:',
                                query_factory=enabled_categories,
                                allow_blank=True)
    submit = SubmitField('Save')
Пример #7
0
class BookmarkForm(FlaskForm):
    """
    bookmark form
    """
    url = URLField('The URL for your bookmark',
                   validators=[DataRequired(), url()])
    description = StringField('Add an optional description')
    tags = StringField('Tags',
                       validators=[
                           Regexp(
                               r'^[a-zA-z0-9, ]*$',
                               message='Tags can only be letters and numbers')
                       ])

    def validate(self):
        """
        custom validator modifies form before validation
        """
        if not (self.url.data.startswith("http://")
                or self.url.data.startswith("https://")):
            self.url.data = "http://" + self.url.data

        if not self.description.data:
            self.description.data = self.url.data

        # filter out empty and dubplicate tags
        stripped = [t.strip() for t in self.tags.data.split(',')]
        not_empty = [tag for tag in stripped if tag]
        tagset = set(not_empty)
        self.tags.data = ','.join(tagset)

        return True if FlaskForm.validate(self) else False
Пример #8
0
class SettingsForm(Form):
    """docstring for SettingsForm"""

    ui_lang = SelectField(
        label=lazy_gettext("Primary site language"),
        description=lazy_gettext("Site will try to show UI labels using this " +
            "language. User data will be shown in original languages."),
    )
    url = URLField(
        label=lazy_gettext("Personal site URL"),
        description=lazy_gettext("If you have personal site and want to share " +
            "with other people, please fill this field"),
        validators=[optional(), url(message=lazy_gettext("Invalid URL."))])
    username = TextField(
        label=lazy_gettext("Public profile address"),
        description=lazy_gettext("Will be part of your public profile URL. Can " +
            "be from 2 up to 40 characters length, can start start from [a-z] " +
            "and contains only latin [0-9a-zA-Z] chars."),
        validators=[
            length(2, 40, message=lazy_gettext("Field must be between 2 and 40" +
            " characters long.")),
            regexp(r"[a-zA-Z]{1}[0-9a-zA-Z]*",
                re.IGNORECASE,
                message=lazy_gettext("Username should start from [a-z] and " +
                    "contains only latin [0-9a-zA-Z] chars"))
        ]
    )
Пример #9
0
class SimplifiedApplicationForm(Form):
    name = TextField(lazy_gettext("Name:"),
                     validators=[required()],
                     widget=AngularJSTextInput(ng_model='embed.name',
                                               ng_enter="submitForm()"),
                     description=lazy_gettext("Name of the resource"))
    age_ranges_range = HiddenField(
        lazy_gettext("Age ranges:"),
        validators=[],
        description=lazy_gettext(
            "Select the age ranges this tool is useful for"))

    # The following are NOT REQUIRED
    description = TextField(
        lazy_gettext("Description:"),
        validators=[],
        widget=AngularJSTextInput(ng_model='embed.description',
                                  ng_enter="submitForm()"),
        description=lazy_gettext("Describe the resource in a few words"))
    domains_text = TextField(
        lazy_gettext("Domains:"),
        validators=[],
        widget=AngularJSTextInput(ng_enter="submitForm()"),
        description=lazy_gettext(
            "Say in which domains apply to the resource (separated by commas): e.g., physics, electronics..."
        ))

    url = URLField(lazy_gettext("Web:"),
                   widget=AngularJSURLInput(ng_model='embed.url',
                                            ng_enter="submitForm()"),
                   description=lazy_gettext("Web address of the resource"))
    height = HiddenField(lazy_gettext("Height:"),
                         widget=AngularJSHiddenInput(ng_model='embed.height'))
    scale = HiddenField(lazy_gettext("Scale:"),
                        widget=AngularJSHiddenInput(ng_model='embed.scale'))
Пример #10
0
class AccountCreate(FlaskForm):
    name = StringField(u"Name", [validators.DataRequired()])
    recurrence = SelectField(
        u"Recurrence",
        choices=[
            ("monthly", "Monthly"),
            ("other", "Other"),
        ],
    )
    pay_period = SelectField(
        default="-",
        choices=[
            ("", "-"),
            (10, "10th"),
            (25, "25th"),
        ],
    )
    status = BooleanField(
        u"Active",
        default=True,
        render_kw={"value": "1"},
    )
    outstanding = DecimalField(u"Outstanding", default=0)
    tag = StringField(u"Label")
    apr = DecimalField(u"APR", default=0)
    url = URLField(
        u"URL",
        [
            validators.URL(message="URL validation error."),
        ],
    )
Пример #11
0
class EventForm(Form):
    title = StringField(label=_l("Title"),
                        filters=(strip, ),
                        validators=[required()])

    start = DateTimeField(_l("Start"), validators=[required()])
    end = DateTimeField(_l("End"), validators=[required()])

    location = TextAreaField(label=_l("Location"), filters=(strip, ))

    url = URLField(label=_l("URL"), filters=(strip, ))

    description = TextAreaField(
        label=_l("Description"),
        widget=RichTextWidget(allowed_tags=WIDGET_ALLOWED),
        filters=(strip, ),
        validators=[required()])

    def validate_description(self, field):
        field.data = bleach.clean(field.data,
                                  tags=ALLOWED_TAGS,
                                  attributes=ALLOWED_ATTRIBUTES,
                                  styles=ALLOWED_STYLES,
                                  strip=True)

    def validate_end(self, field):
        if self.start.data > self.end.data:
            raise ValidationError(_l("End date/time must be after start"))
Пример #12
0
class PluginSettingsForm(IndicoForm):
    adams_url = URLField(_('ADaMS URL'), [DataRequired()],
                         description=_('The URL of the ADaMS REST API'))
    username = StringField(_('Username'), [DataRequired()],
                           description=_('The login used to authenticate with ADaMS service'))
    password = IndicoPasswordField(_('Password'), [DataRequired()],
                                   description=_('The password used to authenticate with ADaMS service'))
    secret_key = IndicoPasswordField(_('Secret key'), [DataRequired()],
                                     description=_('Secret key to sign ADaMS requests'))
    authorized_users = PrincipalListField(_('Authorized users'), allow_groups=True,
                                          description=_('List of users/groups who can send requests'))
    excluded_categories = MultipleItemsField('Excluded categories', fields=[{'id': 'id', 'caption': 'Category ID'}])
    access_ticket_template = QuerySelectField(_("Access ticket template"), allow_blank=True,
                                              blank_text=_("No access ticket selected"), get_label='title',
                                              description=_("Ticket template allowing access to CERN"))
    earliest_start_dt = IndicoDateTimeField(_("Earliest start date"), [Optional()], default_time=time(0, 0),
                                            description=_("The earliest date an event can start to qualify for CERN "
                                                          "access badges"))
    delete_personal_data_after = TimeDeltaField(_('Delete personal data'), [DataRequired()], units=('days',),
                                                description=_('Personal data will be deleted once the event has '
                                                              'finished and the duration specified here has been '
                                                              'exceeded. Once the data has been deleted, access badges '
                                                              'will not be accessible anymore.'))
    api_username = StringField(_('Username'), [DataRequired()], description=_('The username to access the API'))
    api_password = IndicoPasswordField(_('Password'), [DataRequired()], toggle=True,
                                       description=_('The password to access the API'))

    def __init__(self, *args, **kwargs):
        super(PluginSettingsForm, self).__init__(*args, **kwargs)
        self.access_ticket_template.query = (DesignerTemplate.query
                                             .filter(DesignerTemplate.category_id == 0,
                                                     DesignerTemplate.type == TemplateType.badge)
                                             .order_by(db.func.lower(DesignerTemplate.title)))
Пример #13
0
class UpdateProjectForm(FlaskForm):
    title = StringField(
        lazy_gettext('Tytuł'),
        validators=[
            DataRequired(message=lazy_gettext('To pole jest wymagane.')),
            Length(max=50,
                   message=lazy_gettext(
                       'Tytuł może się składać z maksymalnie 50 znaków.'))
        ])
    file = FileField(
        lazy_gettext('Projekt'),
        validators=[
            FileAllowed(['jpg', 'png', 'pdf'],
                        message=lazy_gettext(
                            'Plik musi mieć rozszerzenie jpg, png lub pdf.'))
        ])
    description = TextAreaField(
        lazy_gettext('Opis projektu'),
        validators=[
            DataRequired(message=lazy_gettext('To pole jest wymagane')),
            Length(max=1000,
                   message=lazy_gettext(
                       'Opis może się składać z maksymalnie 1000 znaków.'))
        ])
    url = URLField(lazy_gettext('Link do dodatkowych materiałów (opcjonalne)'),
                   validators=[
                       optional(),
                       url(message=lazy_gettext('Nieprawidłowy adres URL'))
                   ])
    submit = SubmitField(lazy_gettext('Edytuj'))
Пример #14
0
class AddRecipeForm(FlaskForm):
    image = URLField('Recipe Picture', validators=[DataRequired()])
    name = StringField('Recipe Name',
                       validators=[DataRequired(),
                                   Length(min=4, max=50)])
    notes = StringField('Short Description',
                        validators=[DataRequired(),
                                    Length(min=4, max=100)])
    author = StringField('Author Name',
                         validators=[DataRequired(),
                                     Length(min=4, max=20)])
    course = SelectField('Course',
                         choices=[('main', 'Main'), ('starter', 'Starter'),
                                  ('salad', 'Salad'), ('dessert', 'Dessert')],
                         validators=[DataRequired()])
    cuisine = StringField('Cuisine',
                          validators=[DataRequired(),
                                      Length(min=4, max=20)])
    string_of_files = [
        'Egg\r\nBacon\r\nPepper\r\nNutmeg\r\nSeafood\r\nTurmeric'
    ]
    list_of_files = string_of_files[0].split()
    files = [(x, x) for x in list_of_files]
    allergens = MultiCheckboxField('Allergens', choices=files)
    ingredient = StringField(
        'Ingredients', validators=[DataRequired(),
                                   Length(min=4, max=200)])
    step = StringField('Preparation Steps',
                       validators=[DataRequired(),
                                   Length(min=4, max=200)])
    submit = SubmitField('Submit')
Пример #15
0
class BookmarkForm(FlaskForm):
    url = URLField('Enter URL for your bokmark: ',
                   validators=[DataRequired(), url()])
    description = StringField('Add a description:')
    tags = StringField(
        'Tags: ',
        validators=[
            Regexp(r'^[A-Za-z0-9, ]*$',
                   message="Tags can only contain letters and numbers")
        ])

    def validate(self):
        if not (self.url.data.startswith("http://")
                or self.url.data.startswith("https://")):
            self.url.data = "http://" + self.url.data

        if not FlaskForm.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        #filter out empty and duplicate tag names
        stripped = [t.strip() for t in self.tags.data.split(',')]
        not_empty = [tag for tag in stripped if tag]  #remove empty strings
        tagset = set(not_empty)  #to remove duplicates
        self.tags.data = ",".join(tagset)  #creating comma seperated values

        return True
Пример #16
0
class RegisterForm(Form):
    first_name = StringField('Nome', [validators.Length(min=1, max=30)])

    last_name = StringField('Sobrenome', [validators.Length(min=1, max=70)])

    email = EmailField('Email', [
        validators.DataRequired(message="Email inválido"),
        validators.Email(message="Email inválido")
    ])

    username = StringField('Usuário', [validators.Length(min=4, max=25)])

    password = PasswordField('Senha', [
        validators.DataRequired(),
        validators.EqualTo('confirm', message='Senhas não correspondem')
    ])

    confirm = PasswordField('Corfirmar senha')

    course = SelectField('Curso', choices=cursos)

    linkedIn = URLField('LinkedIn')

    year = IntegerField('Ano de Formatura',
                        [validators.NumberRange(min=2015, max=2030)])
Пример #17
0
class EditModule(Form):
    edit_module_id = HiddenField()  # DJG - don't know if I need this
    name = TextField(
        'Module name',
        validators=[DataRequired('Please enter a name for your module')])
    description = TextAreaField('Brief description')
    notes = TextAreaField('Notes')
    module_objectives = SelectMultipleField('Objectives', choices=[])
    material_type = RadioField(
        'Material Type',
        choices=[('Lecture', 'Lecture'), ('Exercise', 'Exercise'),
                 ('Course',
                  'Course (select individual modules to include later)')],
        default='Lecture',
        validators=[
            DataRequired(
                'Please specify what type of material you are creating')
        ])
    material_source = RadioField(
        'Material Source',
        choices=[('upload', 'Upload video'), ('youtube', 'youtube link')],
        default='upload'
    )  # validators = [DataRequired('Please specify how you are providing the material')])
    material_upload = FileField(
        'Select File'
    )  # DJG - would be nice to have these be DataRequired when they apply     #validators=[DataRequired('Please upload your material')])
    material_youtube = URLField(
        'Enter URL'
    )  # validators=[url, DataRequired('Please provide a link to your material')])
    subtitles = BooleanField('Subtitles', default=False)
    easy_language = BooleanField('Simple Language', default=False)
    extension = BooleanField('Extension Material', default=False)
    for_teachers = BooleanField('Ideas for Teachers', default=False)
Пример #18
0
class UserForm(FlaskForm):
    """Create user instance"""

    first_name = StringField("First name", validators=[DataRequired()])
    last_name = StringField("Last name", validators=[DataRequired()])
    gender = StringField("Gender", validators=[DataRequired()])
    phone = StringField("Phone", validators=[DataRequired()])
    city = StringField("City", validators=[DataRequired()])
    country = StringField("Country", validators=[DataRequired()])
    street = StringField("Street", validators=[DataRequired()])
    email = EmailField("Email", validators=[DataRequired(), Email()])
    picture = URLField("Photo", validators=[DataRequired(), URL()])
    submit = SubmitField("Save")

    def validate_picture(self, field):
        """Validates URL availability
         and picture format.

        :param field: URL field
        """
        if field.data[-4:].lower() != ".jpg":
            raise ValidationError("Image url should end on .jpg")
        try:
            urllib.request.urlopen(field.data)
        except Exception:
            raise ValidationError("URL not available")
Пример #19
0
class AddRecipe(FlaskForm):
    db_cuisines = mongo.db.cuisines
    db_cuisines = db_cuisines.find_one(
        {"_id": ObjectId("5b2bc74ae7179a5892864640")})

    cuisine = convert_to_son_obj(db_cuisines)

    name = StringField("Recipe Name",
                       validators=[InputRequired(),
                                   Length(min=4, max=100)])
    image_url = URLField("Image URL",
                         validators=[InputRequired()],
                         render_kw={"placeholder": "http://..."})
    cuisine = SelectField("Cuisine",
                          choices=cuisine,
                          validators=[InputRequired()])
    servings = SelectField("Servings",
                           choices=[("1", "1"), ("2", "2"), ("3", "3"),
                                    ("4", "4"), ("5", "5")],
                           validators=[InputRequired()])
    ingredients = StringField(
        "Ingredients",
        validators=[InputRequired()],
        description="Separate ingredients with comma",
        render_kw={"placeholder": "white rice, chicken, olive oil"})
    description = TextAreaField("Description", validators=[InputRequired()])
Пример #20
0
class UserForm(FlaskForm):
    id = HiddenField('id')
    roles = SelectMultipleField(
        u'Roles',
        coerce=int,
        description="Choose one or more team roles for yourself.")
    webpage_url = URLField(
        u'Online profile', [length(max=128)],
        description="Link to your website or a social media profile.")
    my_story = TextAreaField(
        u'My story',
        description="A brief bio and outline of the competencies you bring " +
        "into the mix. The top portion of your profile.")
    my_goals = TextAreaField(
        u'My goals',
        description="What brings you here? Share a few words about your " +
        "interests. This is the bottom portion of your profile.")
    username = StringField(
        u'Username',
        [length(max=25),
         UniqueValidator(User, 'username'),
         DataRequired()],
        description="Short and sweet.")
    email = EmailField(
        u'E-mail address', [length(max=80), DataRequired()],
        description="For a profile image, link this address at Gravatar.com")
    password = PasswordField(
        u'Change password', [length(max=128)],
        description="Leave blank to keep your password as it is.")
    submit = SubmitField(u'Save changes')
Пример #21
0
class BookmarkForm(Form):
    url = URLField('The URL for your bookmark',
                   validators=[DataRequired(), url()])
    description = StringField('Add an optional description:')
    tags = StringField(
        'Tags',
        validators=[
            Regexp(r'^[a-zA-Z0-9, ]*$',
                   message="Tags can only contain letters and numbers")
        ])

    def validate(self):
        if not self.url.data.startswith('http://') or\
            self.url.data.startswith('https://'):
            self.url.data = "http://" + self.url.data

        if not Form.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        # filter out empty and duplicate tag names
        stripped = [t.strip() for t in self.tags.data.split(',')
                    ]  # strip all white space
        not_empty = [tag for tag in stripped if tag]  # remove all empty string
        tagset = set(not_empty)  # remove duplicate using set
        self.tags.data = ",".join(tagset)

        return True
Пример #22
0
class ProjectNew(FlaskForm):
    id = HiddenField('id')
    autotext_url = URLField(
        u'Readme', [length(max=2048)],
        description="[Optional] URL to a repository or online documentation " +
        "of your project.")
    name = StringField(
        u'Title',
        [length(max=80),
         UniqueValidator(Project, 'name'),
         DataRequired()],
        description=u"A short project title or team name - you may change " +
        "this later.")
    summary = StringField(
        u'Summary', [length(max=140)],
        description="The headline of your project, in up to 140 characters.")
    category_id = SelectField(u'Category',
                              coerce=int,
                              description=u"Select the category that your " +
                              " challenge addresses.")
    contact_url = StringField(
        u'Contact', [length(max=2048)],
        description="On which channel, or in which room, to find you.")
    longtext = TextAreaField(u'Describe your idea')
    submit = SubmitField(u'Save')
Пример #23
0
class BookmarkForm(FlaskForm):
    url = URLField('The URL for your bookmark',
                   validators=[DataRequired(), url()])
    # if url.error:
    #     print("form: Form errors: {}".format(url.errors))
    # print("dddd")
    description = StringField('description')
    tags = StringField(
        'Tags',
        validators=[
            Regexp(r'^[a-zA-z0-9, ]*$',
                   message="Tags can only contain letters and numbers")
        ])

    def validate(self):
        if not self.url.data.startswith("http://") or \
                self.url.data.startswith("https://"):
            self.url.data = "http://" + self.url.data

        if not FlaskForm.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        # filter not empty and duplicate tag names
        # print(self.tags.data)
        stripped = [t.strip() for t in self.tags.data.split(",")]
        not_empty = [tag for tag in stripped if tag]
        tagset = set(not_empty)
        self.tags.data = ",".join(tagset)

        return True
Пример #24
0
class AddEventForm(FlaskForm):
    """Adding event form"""
    event_title = StringField("Title", [
        DataRequired(message="This field is required."),
        Length(min=3, message="Your title is too short."),
    ])
    host_name = StringField("Host full name", [
        DataRequired(message="This field is required."),
        Length(min=3, message="Your name is too short."),
    ])
    event_link = URLField("Link", [
        DataRequired(message="This field is required."),
        URL(message="Not valid url adress."),
    ])
    start_datetime = DateTimeField("Start date-time", [
        Optional(),
    ],
                                   format='%d-%m-%Y %H:%M')
    estimated_duration = DecimalField("Duration", [
        Optional(),
    ])
    event_categories = SelectMultipleField(
        "Categories",
        [
            Optional(),
        ],
        coerce=int,
    )
    event_description = TextField("Event description", [
        Optional(),
    ])
    # agreement_checkbox = BooleanField("Accept agreement")
    # recaptcha = RecaptchaField()
    submit = SubmitField("Dodaj")
Пример #25
0
class StaffForm(FlaskForm):
    """
    Form for list of staff.
    """
    name = StringField('Nome do servidor:',
                       validators=[DataRequired('Digite o nome do servidor.')])

    rank = StringField(
        'Posição do servidor:',
        validators=[DataRequired('Digite a posição do servidor.')])

    abstract = TextAreaField(
        'Resumo da formação caso da coordenação, e descrição do trabalho caso secretário:',
        validators=[
            DataRequired(
                'Insira um breve resumo sobre a formação acadêmica do servidor.'
            )
        ])

    function = SelectField(
        'Tipo de servidor',
        choices=[('coordination', 'Coordenação'),
                 ('secretariat', 'Secretáriado')],
        validators=[DataRequired('Insira o tipo de servidor')])

    photo = URLField('Foto do servidor')

    index = IntegerField()

    create = SubmitField('Adicionar')
Пример #26
0
class RegisterForm(FlaskForm):
    """ Ye olde user registration form """
    username = StringField('Username',
                           validators=[DataRequired(), Length(min=3, max=25)])
    email = EmailField('Email',
                        validators=[DataRequired(), Email(), Length(min=6, max=40)])
    password = PasswordField('Password',
                             validators=[DataRequired(), Length(min=6, max=40)])
    confirm = PasswordField('Verify password',
                            [DataRequired(), EqualTo('password', message='Passwords must match')])
    webpage_url = URLField(u'Online profile')

    def __init__(self, *args, **kwargs):
        """Create instance."""
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.user = None

    def validate(self):
        """Validate the form."""
        initial_validation = super(RegisterForm, self).validate()
        if not initial_validation:
            return False
        user = User.query.filter_by(username=self.username.data).first()
        if user:
            self.username.errors.append('Username already registered')
            return False
        user = User.query.filter_by(email=self.email.data).first()
        if user:
            self.email.errors.append('Email already registered')
            return False
        return True
Пример #27
0
class ArticleForm(FlaskForm):
    """
    Form for articles
    """
    title = StringField(
        'Titulo do artigo:',
        validators=[DataRequired('Digite o título do artigo.')])

    subtitle = StringField('Subtitulo do artigo(se houver):')

    authors = StringField(
        'Nome do autor(es):',
        validators=[DataRequired('Digite o nome dos autor(es)')])

    edition = IntegerField(
        'Número da edição:',
        validators=[DataRequired('Digite o número da edição')])

    pages = StringField(
        'Número das páginas:',
        validators=[DataRequired('Digite o número das páginas')])

    number = IntegerField('Número:')

    location = StringField('Local de impressão:')

    publisher = StringField('Editora:')

    date = StringField('Data:')

    link = URLField('Link para a revista(Se existir)')

    index = IntegerField()

    create = SubmitField('Adicionar')
Пример #28
0
class ResourceForm(FlaskForm):
    next = HiddenField()
    id = HiddenField('id')
    name = StringField(
        u'Name',
        [length(max=80),
         UniqueValidator(Resource, 'name'),
         DataRequired()])
    user_id = SelectField(u'Owner', coerce=int)
    type_id = RadioField(u'Type', coerce=int, choices=resourceTypeList())
    source_url = URLField(
        u'Link', [length(max=2048)],
        description=u'URL to download or get more information')
    summary = TextAreaField(
        u'Summary', [length(max=140)],
        description=u'How is this useful: in 140 characters or less?')
    content = TextAreaField(
        u'Additional information',
        description=
        u'Describe this resource in detail, Markdown and HTML supported')
    progress_tip = SelectField(
        u'Recommend at',
        coerce=int,
        choices=projectProgressList(True, True),
        description=
        u'Progress level at which this resource should be suggested to teams')
    is_visible = BooleanField(u'Show this resource to participants')
    submit = SubmitField(u'Save')
Пример #29
0
class BoolmarkForm(FlaskForm):
    url = URLField('The URL for your bookmark',
                   validators=[DataRequired(), url()])
    description = StringField('Add an optional description')
    tags = StringField(
        'Tags',
        validators=[
            Regexp(r'^[a-zA-Z0-9, ]*$',
                   message="Tags can contain only letters and numbers")
        ])

    def validate(self):
        if not self.url.data.startswith(
                "http://") and not self.url.data.startswith("https://"):
            self.url.data = "https://" + self.url.data

        # print(self.url.data)
        # sys.stdout.flush()
        if not FlaskForm.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        stripped = [t.strip() for t in self.tags.data.split(',')]
        not_empty = [tag for tag in stripped if tag]
        tagset = set(not_empty)
        self.tags.data = ",".join(tagset)

        return True
Пример #30
0
class AddCupcakeForm(FlaskForm):
    """Form for adding cupcakes."""

    flavor = StringField("Cupcake Flavor")
    size = StringField('Size')
    rating = FloatField("Rating")
    image = URLField("URL to image", validators=[URL(), Optional()])