Ejemplo n.º 1
0
 def _convert_many_to_many(self, col_name, label, description,
                           lst_validators, filter_rel_fields,
                           cascade_rel_fields, form_props):
     query_func = self._get_func_related_query(col_name, filter_rel_fields)
     allow_blank = True
     form_props[col_name] = \
         QuerySelectMultipleField(label,
                                  description=description,
                                  query_factory=query_func,
                                  allow_blank=allow_blank,
                                  validators=lst_validators,
                                  widget=Select2ManyWidget())
     return form_props
Ejemplo n.º 2
0
class ResourceFormCreate(FlaskForm):
    address = StringField("address", [rq(), ln(max=144)])
    type = StringField("type", [rq(), ln(max=144)])
    name = StringField("name/identifier", [rq(), ln(max=144)])
    price = DecimalField("price (€/hour)",
                         [rq(), nr(min=0, max=1000000, message=nr_msg)],
                         rounding=ROUND_DOWN)
    communities = QuerySelectMultipleField("allowed communities",
                                           query_factory=Community.get_all)
    submit = SubmitField("create resource")

    class Meta:
        csrf = False
Ejemplo n.º 3
0
class SearchFormN(FlaskForm):

    dna = QuerySelectMultipleField('Select Element',
                                   validators=[DataRequired()],
                                   query_factory=enabled_dna,
                                   allow_blank=True,
                                   get_label='element')
    nfn = QuerySelectMultipleField('Select Property',
                                   validators=[DataRequired()],
                                   query_factory=enabled_nfn,
                                   allow_blank=True,
                                   get_label='plant_extra')

    def __init__(self, *args, **kwargs):
        #The formdata arg determines from where Flask forms gets submissions.
        if 'formdata' not in kwargs:
            kwargs['formdata'] = request.args
        if 'csrf_enabled' not in kwargs:
            kwargs['csrf_enabled'] = False
        super(SearchFormN, self).__init__(*args, **kwargs)

    submit = SubmitField('Search')
Ejemplo n.º 4
0
class ProfileForm(FlaskForm):
    email = StringField(_l("New Email"), validators=[Email()])
    password = PasswordField(_l("New Password"))
    password2 = PasswordField(_l("New Repeat Password"),
                              validators=[EqualTo("password")])
    topics = QuerySelectMultipleField(_l("Topics"),
                                      query_factory=lambda: Topic.query)
    submit = SubmitField(_l("Save"))

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is not None and user.id != current_user.id:
            raise ValidationError(_("Please use a different email address."))
Ejemplo n.º 5
0
class CreateOrganizationForm(FlaskForm):
    name = StringField('Organizaton name', validators=[DataRequired()])
    description = TextAreaField('Description')

    main_orgs = QuerySelectMultipleField(
        'Main Organization',
        query_factory=orgs,
        allow_blank=False,
        get_label='name',
        get_pk=lambda x: x.id,
        blank_text=u'Select a main organization...')

    submit = SubmitField('Submit')
Ejemplo n.º 6
0
class BookForm(FlaskForm):
    """Form to create a book."""
    title = StringField('Book Title',
                        validators=[DataRequired(),
                                    Length(min=3, max=80)])
    publish_date = DateField('Date Published')
    author = QuerySelectField('Author',
                              query_factory=lambda: Author.query,
                              allow_blank=False)
    audience = SelectField('Audience', choices=Audience.choices())
    genres = QuerySelectMultipleField('Genres',
                                      query_factory=lambda: Genre.query)
    submit = SubmitField('Submit')
Ejemplo n.º 7
0
class ProfileCreateForm(ProfileCreateFormBase):
    multipart = True
    next = HiddenField()
    networks = QuerySelectMultipleField(
        query_factory=lambda: current_user.networks)
    email = EmailField(u'Email', [Required(), Email()])
    name = TextField(u'Name', [Required(), Length(max=100)])
    password = PasswordField(u'Password', [Required(), Length(max=100)])
    password1 = PasswordField(u'Retype-password',
                              [Required(), Length(max=100)])
    role_code = RadioField(_("Role"),
                           [AnyOf([str(val) for val in USER_ROLE.keys()])],
                           choices=[])
    # Don't use the same name as model because we are going to use populate_obj().
    avatar_file = FileField(u"Avatar", [Optional()])
    gender_code = RadioField(u"Gender",
                             [AnyOf([str(val) for val in GENDER_TYPE.keys()])],
                             choices=[(str(val), label)
                                      for val, label in GENDER_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()])
    location = TextField(u'Location', [Length(max=64)])
    bio = TextAreaField(u'Bio', [Length(max=1024)])
    submit = SubmitField(u'Save')

    def get_role_codes(self, role_code):
        if role_code == 0:
            return [(str(k), v) for k, v in USER_ROLE.items()]
        elif role_code == 3:
            return [(str(k), v) for k, v in USER_ROLE.items() if k in (3, 4)]
        elif role_code == 1:
            return [(str(k), v) for k, v in USER_ROLE.items()
                    if k in (1, 2, 3, 4)]

    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))

    def validate_password(self, field):
        if field.data != self.password1.data:
            raise ValidationError("The Passwords Don't Match")

    def validate_name(self, field):
        if User.query.filter_by(name=field.data).first() is not None:
            raise ValidationError(_('This username is already registered'))

    def validate_email(self, field):
        if User.query.filter_by(email=field.data).first() is not None:
            raise ValidationError(_('This email is already registered'))
Ejemplo n.º 8
0
class CreateMatchForm(FlaskForm):
    winners = QuerySelectMultipleField(
        'Winners',
        validators=[DataRequired()],
        query_factory=get_players,
        id='selectpicker_w',
    )
    losers = QuerySelectMultipleField(
        'Losers',
        validators=[DataRequired()],
        query_factory=get_players,
        id='selectpicker_l',
    )
    winner_score = SelectField('Winning Score',
                               choices=[(k, k) for k in range(11)],
                               coerce=int,
                               default=10,
                               validators=[my_check_scores])
    loser_score = SelectField('Losing Score',
                              choices=[(k, k) for k in range(11)],
                              coerce=int,
                              default=0,
                              validators=[my_check_scores])

    importance = SelectField('Match Importance',
                             choices=[(k, k) for k in [8, 16, 32]],
                             coerce=int,
                             default=16)
    timestamp = DateTimeField("Match played at",
                              default=copenhagen_now,
                              id='datepick')
    submit = SubmitField('Submit')

    def validate_losers(self, losers):
        for l in losers.data:
            if l in self.winners.data:
                raise ValidationError(
                    'Same user cannot be both winner and loser')
Ejemplo n.º 9
0
class BlogPostForm(FlaskForm):
    title = StringField("Title", validators=[InputRequired()])
    text = CKEditorField("Body", validators=[InputRequired()])
    image = FileField(
        "Image",
        validators=[InputRequired(),
                    FileAllowed(images, "Images only!")])
    categories = QuerySelectMultipleField(
        "Categories",
        validators=[InputRequired()],
        get_label="name",
        query_factory=lambda: db.session.query(BlogCategory).order_by("order"),
    )
    tags = QuerySelectMultipleField(
        "Tags",
        validators=[InputRequired()],
        get_label="name",
        query_factory=lambda: db.session.query(BlogTag).order_by("created_at"),
    )
    newsletter = BooleanField("Send Announcement To Subscribers.")
    all_users = BooleanField("Send Announcement To All Users.")

    submit = SubmitField("Submit")
Ejemplo n.º 10
0
class VenueForm(FlaskForm):
    name = StringField("name", validators=[DataRequired()])
    address = StringField("address", validators=[DataRequired()])

    city = FormField(CityForm)

    genres = QuerySelectMultipleField(
        "genres",
        validators=[DataRequired()],
        query_factory=genre_choices,
        get_label="name",
    )

    contact_info = FormField(ContactInfoForm)
Ejemplo n.º 11
0
class ProgramForm(Form):
    # can't use model_form, because we want to use a custom field for time duration
    name = StringField()
    description = TextAreaField()
    program_structure = TextAreaField(description=_(
        "Drag content here in desired order, double click to reset"))
    structure = TextAreaField(u'')
    duration = DurationField(
        description=_("Duration of the program, in HH:MM(:SS)"))
    # language = QuerySelectField(query_factory=all_languages,allow_blank=False)
    # program_type = QuerySelectField(query_factory=all_program_types,allow_blank=False)
    networks = QuerySelectMultipleField(_('Networks'), [Required()],
                                        query_factory=all_networks)
    submit = SubmitField(_('Save'))
Ejemplo n.º 12
0
class OpsRole(FlaskForm):
    u"""
    角色操作
    """
    name = StringField(u"角色名称", validators=[Required()])
    display_name = StringField(u"显示名称", validators=[Required()])
    status = BooleanField(u"是否启用", validators=[Required()], default=True)
    permissions = QuerySelectMultipleField(
        u"权限列表",
        query_factory=lambda: Permission.query.all(),
        get_pk=lambda x: x.id,
        get_label=lambda x: x.name,
    )
    submit = SubmitField(u"确认")
Ejemplo n.º 13
0
class MarkdownForm(ArticleForm):
    body = TextAreaField(
        '文章HTML代码',
        validators=[DataRequired(),
                    Length(min=50, message='文章最少50字符')])
    markdown = TextAreaField(
        'Markdown源码',
        validators=[DataRequired(),
                    Length(min=50, message='最好50字符')])
    tags = QuerySelectMultipleField('文章分类',
                                    query_factory=tag_list,
                                    get_label='name',
                                    allow_blank=True,
                                    blank_text='选择文章标签')
Ejemplo n.º 14
0
class TicketTypeForm(forms.Form):
    title = forms.StringField(
        __("Title"),
        validators=[forms.validators.DataRequired()],
        filters=[forms.filters.strip()],
    )
    ticket_events = QuerySelectMultipleField(
        __("Events"),
        widget=ListWidget(),
        option_widget=CheckboxInput(),
        allow_blank=True,
        get_label='title',
        query_factory=lambda: [],
    )
Ejemplo n.º 15
0
class CreateModerForm(FlaskForm):
    from app import create_app
    app = create_app(config_class=Config)
    with app.app_context():
        group = QuerySelectMultipleField('Группа',
                                         query_factory=Group.query.all,
                                         get_pk=lambda group: group.id,
                                         get_label=lambda group: group.name)
        user = QuerySelectField(
            'Пользователь',
            query_factory=User.query.filter(User.role == 'admin').all,
            get_pk=lambda user: user.tg_id,
            get_label=lambda user: user.first_name)
        submit = SubmitField('Добавить')
Ejemplo n.º 16
0
class ClipForm(FlaskForm):
    category_id = QuerySelectMultipleField(
        "Category", [validators.data_required()],
        get_label="name",
        query_factory=lambda: models.Category.query.filter_by(
            account_id=current_user.id).all())

    content = TextAreaField(
        "Content",
        [validators.Length(min=2, max=4096),
         validators.data_required()])

    class Meta:
        csrf = False
Ejemplo n.º 17
0
class SourceForm(ModelForm):
    class Meta:
        model = Source

    __order = ('name', 'organisations')

    def __iter__(self):
        f = list(super(ModelForm, self).__iter__())
        get_field = lambda field_id: next(
            (fld for fld in f if fld.id == field_id))
        return (get_field(field_id) for field_id in self.__order)

    organisations = QuerySelectMultipleField(
        query_factory=organisation_factory, get_label='name')
Ejemplo n.º 18
0
class Form_Record_Add(Form):
    email = StringField('email',
                        validators=[
                            validators.DataRequired(),
                            validators.Length(max=255,
                                              message='max 255 characters')
                        ])
    username = StringField('username',
                           validators=[
                               validators.DataRequired(),
                               validators.Length(max=255,
                                                 message='max 255 characters')
                           ])

    # MANY-TO-MANY
    sections = QuerySelectMultipleField(
        'Select Sections',
        query_factory=lambda: Section.query.filter(Section.is_active == True
                                                   ).all(),
        get_label=lambda s: s.title_en_US,
        allow_blank=True)
    # MANY-TO-MANY
    in_addresses = QuerySelectMultipleField(
        'Select In_addresses',
        query_factory=lambda: Address.query.filter(Address.is_active == True
                                                   ).all(),
        get_label=lambda s: s.title_en_US,
        allow_blank=True)

    # MANY-TO-MANY
    in_events = QuerySelectMultipleField('Select In_events',
                                         query_factory=lambda: Event.query.
                                         filter(Event.is_active == True).all(),
                                         get_label=lambda s: s.title_en_US,
                                         allow_blank=True)

    is_active = BooleanField('is_active', default=True)
Ejemplo n.º 19
0
class SubmissionEditForm(FlaskForm):
    obj_id = HiddenField()
    pending_cover_img = FileField('Cover Image', validators=[Length(max=500)])
    title = StringField(f'Title{required}', validators=[DataRequired(), Length(max=150)])
    subtitle = StringField('Subtitle', validators=[Length(max=150)])
    synopsis = TextAreaField(f'Synopsis{required}', validators=[DataRequired(), Length(max=1000)],
            render_kw={'rows': '6'})
    genres = QuerySelectMultipleField(f'Genres{required}', 
            render_kw={'data_type': 'select2'}, 
            description="<small class='text-muted'>Pick up to two genres.</small>", 
            query_factory=all_genres)
    tags = QuerySelectMultipleField('Tags', 
            render_kw={'data_type': 'select2'}, 
            description="<small class='text-muted'>Pick up to ten tags.</small>", 
            query_factory=all_tags)
    links = FieldList(FormField(LinkForm), min_entries=1, max_entries=5, label=f'Links{required}')
    rating = SelectField(f'Rating{required}', validators=[DataRequired()])
    #website = StringField('URL', validators=[DataRequired(), Length(max=300)])
    #author_placeholder = StringField('Author')
    status = SelectField(f'Status{required}')
    words = IntegerField(f'Current Word Count{required}', render_kw={'placeholder': '###'})
    frequency = FloatField(f'Releases per Month{required}', render_kw={'placeholder': 'Decimals are allowed'})
    author_claim = BooleanField(f'Are you the Author?{required}', description="<small class='text-muted'>By checking this box you agree that you hold the copyright to this work and have the rights to upload it here.</small>")

    def validate_genres(self, genres):
        if len(self.genres.data) > 2:
            raise ValidationError('You can only pick up to two genres.')

    def validate_tags(self, tags):
        if len(self.tags.data) > 2:
            raise ValidationError('You can only pick up to ten tags.')

    def validate_links(self, genres):
        if len(self.links.data) < 1:
            raise ValidationError('You must provide at least one link.')
        if len(self.links.data) > 5:
            raise ValidationError('You can only provide up to five links.')
Ejemplo n.º 20
0
class UserEditForm(FlaskForm):
    email = StringField(f'Email{required}',
                        validators=[DataRequired(),
                                    Email(),
                                    Length(max=120)])
    username = StringField('Username', validators=[Length(max=20)])
    first_name = StringField('First Name', validators=[Length(max=50)])
    last_name = StringField('Last Name', validators=[Length(max=50)])
    groups = QuerySelectMultipleField('Groups',
                                      query_factory=all_groups,
                                      allow_blank=True,
                                      render_kw={'data-type': 'select2'})
    company = StringField('Company', validators=[Length(max=100)])
    phone = StringField('Phone Number', validators=[Length(max=12)])
    subscribed = BooleanField('Subscribed?')
Ejemplo n.º 21
0
class FictionEditForm(FlaskForm):
    obj_id = HiddenField()
    pending_cover_img = FileField('Cover Image')
    title = StringField('Title', validators=[DataRequired(), Length(max=150)])
    subtitle = StringField('Subtitle', validators=[Length(max=150)])
    synopsis = TextAreaField('Synopsis', validators=[DataRequired(), Length(max=1000)],
            render_kw={'rows': '6'})
    genres = QuerySelectMultipleField('Genres', render_kw={'data_type': 'select2'}, query_factory=all_genres)
    tags = QuerySelectMultipleField('Tags', 
            render_kw={'data_type': 'select2'}, 
            description="<small class='text-muted'>Pick up to ten tags.</small>", 
            query_factory=all_tags)
    links = FieldList(FormField(LinkForm), max_entries=5, label=f'Links{required}')
    status = SelectField('Status')
    words = IntegerField('Current Word Count')
    frequency = FloatField('Releases per Month')

    def validate_genres(self, genres):
        if len(self.genres.data) > 2:
            raise ValidationError('You can only pick up to two genres.')

    def validate_tags(self, tags):
        if len(self.tags.data) > 10:
            raise ValidationError('You can only pick up to ten tags.')
Ejemplo n.º 22
0
class RecipeForm(FlaskForm):
    name = StringField("Recipe name", [validators.Length(min=2, max=144)])
    ingredients = TextAreaField("Ingredients", [validators.Length(min=2, max=500)])
    recipetext = TextAreaField("Recipe", [validators.Length(min=2, max=1000)])
    tips = TextAreaField("Extra tips", [validators.Length(max=500)])
    categories = QuerySelectMultipleField(
        'Categories',
        query_factory=lambda: Category.query.all(),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        get_label=lambda item: item.name
    )

    class Meta:
        csrf = False
Ejemplo n.º 23
0
 class UpdateEventForm(EventForm):
     category = QuerySelectField('Update Category',
                                 validators=[DataRequired()],
                                 query_factory=category_query,
                                 get_label='name',
                                 allow_blank=True,
                                 blank_text='Choose Category',
                                 default=Category.query.filter_by(
                                     name=default_category_name).first())
     tags = QuerySelectMultipleField('Update Tag(s)',
                                     query_factory=tag_query,
                                     get_label='name',
                                     default=Tag.query.filter(
                                         Tag.events.any(id=event_id)).all())
     submit = SubmitField('Update')
Ejemplo n.º 24
0
class CreateEventForm(FlaskForm):
    name = StringField('Organizaton name', validators=[DataRequired()])
    description = TextAreaField('Description')

    org = QuerySelectMultipleField('Organization',
                                   query_factory=orgs,
                                   allow_blank=False,
                                   get_label='name',
                                   get_pk=lambda x: x.id,
                                   blank_text=u'Select a organization...')

    start_time = DateField('Start', format='%m/%d/%y', validators=[Required()])
    end_time = DateField('End', format='%m/%d/%y', validators=[Required()])

    submit = SubmitField('Submit')
Ejemplo n.º 25
0
class LiveRecordingForm(FlaskForm):
    """
    Form to add a live recording
    """

    date = DateField('Date', validators=[DataRequired()], format='%Y-%m-%d')
    time = TimeField('Time')
    location = QuerySelectField(query_factory=lambda: Location.query.all(),
                                get_label="name")
    engineers = QuerySelectMultipleField(
        query_factory=lambda: Employee.query.join(
            Role, (Role.id == Employee.role_id)).filter(
                Role.name.endswith('Engineer')).all(),
        get_label="username")
    submit = SubmitField('Submit')
Ejemplo n.º 26
0
class PostForm(Form):
    title = StringField('Название')
    text = CKEditorField('Текст')
    is_published = BooleanField('Опубликовано')
    tags = QuerySelectMultipleField(
        query_factory=enabled_tags,
        get_label=lambda tag: tag.name,
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput())
    category = QuerySelectField(
        'Категория',
        query_factory=enabled_categories,
        get_label=lambda category: category.name,
    )
    photo = FileField(
        'Картинка',
        validators=[FileAllowed(['png', 'jpg', 'jpeg'], 'Images only!')])

    def valid_photo(self):

        if 'photo' not in request.files:
            flash('Файл не загружен', 'danger')
            return False

        post_file = request.files['photo']
        if post_file.filename == '':
            flash('Файл не выбран', 'danger')
            return False

        if not allowed_file(post_file.filename):
            flash('Неверное расширение ффайла', 'danger')
            return False

        return True

    def upload_photo(self, old_photo=''):
        if not self.valid_photo():
            return False

        post_file = request.files['photo']
        filename = secure_filename(post_file.filename)
        photo = 'photos/' + filename
        post_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

        if old_photo:
            os.remove(os.path.join(app.config['UPLOAD_FOLDER'], old_photo))

        return photo
Ejemplo n.º 27
0
class MealForm(FlaskForm):
    """Form for creating a new meal"""
    name = StringField('Name', validators=[Length(min=3, max=80)])
    img_url = StringField(
        'Image Url',
        validators=[DataRequired(),
                    URL(), Length(min=3, max=300)])
    description = StringField(
        'Description', validators=[DataRequired(),
                                   Length(min=3, max=300)])
    recipes = QuerySelectMultipleField(
        'Recipe',
        query_factory=lambda: Recipe.query.filter_by(created_by_id=current_user
                                                     .id))

    submit = SubmitField('Submit')
Ejemplo n.º 28
0
class BookForm(FlaskForm):
    """Form to create a book."""
    title = StringField('Book Title', 
        validators=[
            DataRequired(), 
            Length(min=3, max=80, message="Your message needs to be betweeen 3 and 80 chars")
        ])
    publish_date = DateField('Date Published', validators=[DataRequired()])
    author = QuerySelectField('Author', query_factory=lambda: Author.query, allow_blank=False)
    audience = SelectField('Audience', choices=Audience.choices())
    genres = QuerySelectMultipleField('Genres', query_factory=lambda: Genre.query)
    submit = SubmitField('Submit')

    def validate_title(form, field):
        if 'banana' in field.data:
            raise ValidationError('Title cannot contain the word banana')
Ejemplo n.º 29
0
class ArticleForm(FlaskForm):
    article_type = SelectField('Type',
                               choices=[('Guide', 'Guide'), ('Blog', 'Blog'),
                                        ('News', 'News')])
    title = StringField(
        'Title', validators=[DataRequired('Article must have a title!')])
    # country_tag = SelectMultipleField(
    #     'Country tags', choices=[(country.name, country.name)
    #                              for country in Country.get_country_list()])
    country_tag = QuerySelectMultipleField(label='Country tags',
                                           get_label='name',
                                           query_factory=lambda: Country.query)
    # body = TextAreaField(
    #     'Post body', validators=[DataRequired('Article must have some text!')])
    hidden_body = HiddenField()
    submit = SubmitField()
Ejemplo n.º 30
0
class ChooseBestMatchupForm(FlaskForm):
    players = QuerySelectMultipleField(
        'Players',
        validators=[DataRequired()],
        query_factory=sort_players,
        id='selectpicker_best',
    )
    rating_type = SelectField('Rating to use',
                              choices=[
                                  ('elo', 'Elo'),
                                  ('trueskill', 'Trueskill'),
                                  ('goal_difference', 'Goal difference'),
                                  ('matches_played', 'Matches Played'),
                              ],
                              default='elo')
    submit = SubmitField('Submit')