Example #1
0
class PasswordResetRequestForm(FlaskForm):
    # TODO: add placeholder
    email = StringField(_l(u'Email'),
                        validators=[InputRequired(),
                                    Length(1, 64),
                                    Email()])
    submit = SubmitField(_l(u'Reset Password'))  # 发送重置密码邮件
Example #2
0
class PostEditorForm(FlaskForm):
    title = StringField(_l(u'Tittle'), [InputRequired()])
    body = PageDownField(_l(u'Enter your Markdown'), [InputRequired()])
    is_public = BooleanField(_l(u'Only visible for myself'))
    # TODO: add tags field
    # tags =
    submit = SubmitField(_l(u'Publish now'))
Example #3
0
class CompareCityForm(FlaskForm):
    # numCountries = StringField('Num COuntries', validators=[DataRequired()])
    cities = SelectField(_l('Please choose a city'),
                         choices=[(c, c)
                                  for c in get_all_places(level='cities')],
                         validators=[DataRequired()])
    submit = SubmitField(_l('Show Report'))
Example #4
0
class ChoiceEditorForm(EditorForm):
    value = wtf.StringField(_l('Value'),
                            validators=[wtf.validators.DataRequired()])
    points = wtf.FloatField(_l('Points'),
                            default=0,
                            validators=[wtf.validators.Optional()])
    max_levenshtein_distance = wtf.IntegerField(
        _l('Flexibility (1-5)'),
        default=3,
        validators=[wtf.validators.NumberRange(min=1, max=5)])

    submit = wtf.SubmitField(_l('Save'),
                             render_kw={'class_': 'btn btn-success'})
    delete = wtf.SubmitField(_l('Remove'),
                             render_kw={'class_': 'btn btn-danger'})

    def __init__(self,
                 choice: model.Choice = None,
                 question: model.Question = None,
                 *args,
                 **kwargs):
        if choice is None:
            if question is None or question.id is None:
                raise ValueError('Question must be provided for new choice!')
            else:
                choice = model.Choice(question_id=question.id)
        super().__init__(choice, *args, **kwargs)
Example #5
0
    def from_model(cls, question: model.Question, fill: model.FilledQuiz,
                   *args, **kwargs):
        class Form(QuestionForm):
            pass

        if question.show_choices:
            if question.multiple:
                Form.answer = QuerySelectMultipleField(
                    '',
                    query_factory=choices(question),
                    get_pk=lambda x: x.id,
                    get_label=lambda x: x.value)
                Form.submit = wtf.SubmitField(_l('Save'))
            else:
                Form.answer = wtf.RadioField('',
                                             choices=[
                                                 (x.id, x.value)
                                                 for x in choices(question)()
                                             ],
                                             coerce=int)
                Form.submit = wtf.SubmitField(_l('Save'))
        else:
            Form.answer = wtf.StringField(
                '', validators=[wtf.validators.Length(max=255)])
            Form.submit = wtf.SubmitField(_l('Save'))

        form = Form(fill, question, *args, **kwargs)
        return form
Example #6
0
class BlockEditorForm(EditorForm):
    order_number = wtf.IntegerField(_l('Order Number'),
                                    validators=[wtf.validators.DataRequired()])
    name = wtf.StringField(_l('Name'),
                           validators=[wtf.validators.DataRequired()])
    check_time = wtf.IntegerField(_l('Check Time'),
                                  default=120,
                                  validators=[wtf.validators.DataRequired()])
    submit = wtf.SubmitField(_l('Save'),
                             render_kw={'class_': 'btn btn-success'})
    delete = wtf.SubmitField(_l('Remove'),
                             render_kw={'class_': 'btn btn-danger'})

    def __init__(self,
                 block: model.Block = None,
                 quiz: model.Quiz = None,
                 *args,
                 **kwargs):
        if block is None:
            if quiz is None or quiz.id is None:
                raise ValueError('Quiz must be provided for new block!')
            else:
                latest = quiz.blocks\
                    .order_by(model.Block.order_number.desc())\
                    .first()

                if latest is None:
                    order_number = 1
                else:
                    order_number = latest.order_number + 1
                block = model.Block(quiz_id=quiz.id, order_number=order_number)

        super().__init__(block, *args, **kwargs)
Example #7
0
class QuestionEditorForm(EditorForm):
    order_number = wtf.IntegerField(_l('Order Number'),
                                    validators=[wtf.validators.DataRequired()])
    time = wtf.IntegerField(_l('Time'),
                            validators=[wtf.validators.DataRequired()])
    show_choices = wtf.BooleanField(_l('Show Choices'),
                                    validators=[wtf.validators.Optional()])
    content = wtf.TextAreaField()

    submit = wtf.SubmitField(_l('Save'),
                             render_kw={'class_': 'btn btn-success'})
    delete = wtf.SubmitField(_l('Remove'),
                             render_kw={'class_': 'btn btn-danger'})

    def __init__(self,
                 question: model.Question = None,
                 block: model.Block = None,
                 *args,
                 **kwargs):
        if question is None:
            if block is None or block.id is None:
                raise ValueError('Block must be provided for new question!')
            else:
                latest = block.questions\
                    .order_by(model.Question.order_number.desc())\
                    .first()

                if latest is None:
                    order_number = 1
                else:
                    order_number = latest.order_number + 1
                question = model.Question(block_id=block.id,
                                          order_number=order_number)
        super().__init__(question, *args, **kwargs)
Example #8
0
class BookForm(FlaskForm):
    title = TextField(_l('Title'),[validators.InputRequired()])
    publisher = TextField(_l('Publisher'),[validators.InputRequired()])
    author = TextField(_l('Author'))
    isbn13 = TextField('ISBN 13',[validate_isbn13])
    category = SelectField(_l('Category'), choices=book_categories)
    submit = SubmitField(_l('Save'))
Example #9
0
class MultipleChoiceForm(GenericForm):
    number_of_choices = wtf.IntegerField(
        _l('Number of Choices'),
        validators=[wtf.validators.DataRequired()],
        default=4
    )
    submit = wtf.SubmitField(_l('Create Section'))

    def create(self, quiz: md.Quiz):
        section = md.Section(
            user_id=current_user.id,
            container=quiz,
            order_number=self.order_number.data,
            name=self.name.data
        )
        md.db.session.add(section)

        for i in range(self.number_of_questions.data):
            question = md.Question(
                text=self.question_text.data or _('Question %(num)s', num=i+1),
                order_number=i+1,
                show_values=True,
                container=section
            )
            md.db.session.add(question)
            for j in range(self.number_of_choices.data):
                md.db.session.add(md.Value(
                    text=_('Answer'),
                    question=question,
                    order_number=j+1,
                    points=0
                ))

        return section
Example #10
0
class ExtendedLoginForm(LoginForm):

    email = StringField(_l('Email or Username'),
                        validators=[Required('Email required')])
    password = PasswordField(_l('Password'),
                             validators=[Required('Password required')])
    remember = BooleanField(_l('Remember Me'))
    submit = SubmitField(_l('Login'))
Example #11
0
class PasswordResetForm(FlaskForm):
    password = PasswordField(_l(u'New Email'),
                             validators=[
                                 InputRequired(),
                                 EqualTo('password2',
                                         message='Passwords must match')
                             ])  # 两次输入的密码必须相同。
    password2 = PasswordField(_l(u'Confirm password'),
                              validators=[InputRequired()])  # 再次输入新密码
    submit = SubmitField(_l(u'Reset Password'))  # 重置密码
Example #12
0
class LoginUserForm(LoginForm):
    email = wtf.StringField(_l('Username'),
                            validators=[
                                wtf.validators.DataRequired(),
                                wtf.validators.Length(min=5, max=16)
                            ])
    password = wtf.PasswordField(_l('Password'),
                                 validators=[wtf.validators.DataRequired()])
    remember = wtf.BooleanField(_l('Remember Me'), default=True)
    submit = wtf.SubmitField(_l('Sign in'))
Example #13
0
class SubmitEventRequestForm(FlaskForm):
    country = SelectField(_l('Please choose a place'),
                          choices=[(c, c)
                                   for c in get_all_places(level='countries')],
                          validators=[DataRequired()])
    date = DateTimeField(_l('Event date'), validators=[DataRequired()])
    desc = StringField(_l('Briefly describe the event'),
                       validators=[DataRequired()])
    fulltext = TextAreaField(_l('Describe the event in detail'),
                             validators=[DataRequired()])
    submit = SubmitField(_l('Submit event'))
Example #14
0
class LoginForm(FlaskForm):
    # TODO: add placeholder
    email = StringField(_l(u'Email'),
                        validators=[InputRequired(),
                                    Length(1, 64)])
    password = PasswordField(_l(u'Password'),
                             validators=[InputRequired(),
                                         Length(1, 64)])
    remember = BooleanField(_l(u'Keep me logged in'))
    # forgot_password = Label('', _l(u'Forget your password? Click here!'))
    submit = SubmitField(_l(u'Log In'))
Example #15
0
class ChangePasswordForm(FlaskForm):
    old_password = PasswordField(_l(u'Old password'),
                                 validators=[InputRequired()])
    password = PasswordField(_l(u'New password'),
                             validators=[
                                 InputRequired(),
                                 EqualTo('password2',
                                         message='Passwords must match.')
                             ])
    password2 = PasswordField(_l(u'Confirm new password'),
                              validators=[InputRequired()])
    submit = SubmitField(_l(u'Update Password'))
Example #16
0
class FilledQuizView(ModelView):
    roles = ['editor']

    columns = {
        'user': _l('User'),
        'quiz': _l('Quiz'),
        'points': _l('Points')
    }

    @property
    def _column_filters(self):
        # noinspection PyTypeChecker
        return [query_filter(model.User)]
Example #17
0
class AnswerView(ModelView):
    roles = ['editor']

    columns = {
        'question': _l('Question'),
        'quiz.user': _l('User'),
        'value': _l('Answer'),
        'points': _l('Points')
    }
    @property
    def _column_filters(self):
        # noinspection PyTypeChecker
        return [query_filter(model.FilledQuiz)]
Example #18
0
class QuizEditorForm(EditorForm):
    name = wtf.StringField(_l('Name'),
                           validators=[wtf.validators.DataRequired()])
    start_time = DateTimeField(_l('Start Time'),
                               validators=[wtf.validators.Optional()])
    public = wtf.BooleanField(_l('Public'),
                              validators=[wtf.validators.Optional()])
    submit = wtf.SubmitField(_l('Save'),
                             render_kw={'class_': 'btn btn-success'})

    def __init__(self, quiz: model.Quiz = None, *args, **kwargs):
        if quiz is None:
            quiz = model.Quiz()
        super().__init__(quiz, *args, **kwargs)
Example #19
0
class EditProfileForm(FlaskForm):
    # TODO: add placeholder
    avatar = FileField(
        _l(u'Change avatar'),
        validators=[image_only],
        render_kw={"accept": ', '.join(['image/' + ext for ext in IMAGES])})
    # avatar = FileField(_l(u'Change avatar', validators=[FileAllowed(avatar, _l(u'Images only'))]))
    name = StringField(_l(u'Nickname'),
                       validators=[InputRequired(),
                                   Length(0, 64)])
    location = StringField(_l(u'Location'), validators=[Length(0, 64)])
    description = TextAreaField(_l(u'description'))
    # locale = SelectField(_l(u'Locale'), choices=supported_languages)
    submit = SubmitField(_l(u'Save profile'))
Example #20
0
class ChangeEmailForm(FlaskForm):
    email = StringField(_l(u'New Email'),
                        validators=[InputRequired(),
                                    Length(1, 64),
                                    Email()])
    password = PasswordField(_l(u'Password'), validators=[InputRequired()])
    submit = SubmitField(_l(u'Update Email Address'))

    def validate_email(self, field):
        if User.query.filter_by(email=field.data.lower()).first():
            raise ValidationError(_l(u'Email already registered.'))
        if self.email == field.data.lower():
            raise ValidationError(_l(
                u'Your are using the old email address.'))  # 您输入的电子邮箱与之前的相同。
Example #21
0
def edit(id):
    qry = db.session.query(Book).filter(Book.id==id)
    book = qry.first()

    if book:
        form = BookForm(formdata=request.form, obj=book)
        if request.method == 'POST' and form.validate():
            # Save modifications
            save_changes(book, form)
            flash(_l(u'Book updated successfully!'),'success')
            return redirect('/')
        return render_template('books/edit_book.html', form=form)
    else:
        flash(_l(u'ERROR Book #{id} doesn''t exist').format(id=id))
        return redirect(url_for('.index'))
Example #22
0
class RegisterUserForm(RegisterForm):
    username = wtf.StringField(_l('Username'),
                               validators=[
                                   wtf.validators.DataRequired(),
                                   wtf.validators.Length(min=5, max=16)
                               ])
    email = None
    password = wtf.PasswordField(_l('Password'),
                                 validators=[wtf.validators.DataRequired()])
    password_confirm = wtf.PasswordField(_l('Confirm Password'),
                                         validators=[
                                             wtf.validators.DataRequired(),
                                             wtf.validators.EqualTo('password')
                                         ])
    submit = wtf.SubmitField(_l('Register'))
Example #23
0
def search_results(search_string=None):
    results = []
    search = BookSearchForm()

    if search.validate_on_submit():
        return redirect(url_for('.search_results', search_string=search.search.data))

    if search_string:
        search_string_list = search_string.split(' ')
        qry=Book.query.filter(Book.title.contains(search_string))
        for string in search_string_list:
            subquery = Book.query.filter(or_(Book.title.contains(string),
                                        Book.author.contains(string),
                                        Book.publisher.contains(string),
                                        Book.isbn13.contains(string),
                                        Book.category.contains(string)))
            qry = qry.union(subquery)
        results = qry.all()
    else:
        results = Book.query.all()
 
    if not results:
        message = gettext(u'No results found!') 
        flash(message,'info')
        return redirect(url_for('.search'))
    else:
        # display results
        table = BookResults(results)
        search.search.data = search_string
        if current_user.has_roles('Admin'):
            table.add_column('edit', LinkCol(_l(u'Edit'),'.edit',url_kwargs=dict(id='id')))
        table.border = True
        return render_template('books/results.html', table=table, form=search)
Example #24
0
class QuizView(ModelView):
    columns = {
        'hosts': _l('Hosts'),
        'name': _l('Name'),
        'start_time': _l('Start Time'),
        'end_time': _l('End Time'),
        'password': _l('Password')
    }

    form_excluded_columns = ['sections', 'last_updated']
    edit_template = 'editor/quiz.html'

    def get_query(self):
        if not current_user.has_role('admin'):
            return current_user.quizzes

        return md.Quiz.query

    def get_count_query(self):
        ids = [q.id for q in current_user.quizzes]

        if not current_user.has_role('admin'):
            return md.db.session.query(sa.func.count(md.Quiz.id)).filter(
                md.Quiz.id.in_(ids))

        return md.db.session.query(sa.func.count(md.Quiz.id))

    def check_access(self):
        if current_user.has_role('admin'):
            return

        quiz = md.Quiz.query.get(request.args.get('id'))
        if quiz and current_user not in quiz.hosts:
            return abort(403)

    @expose('/edit/', methods=('GET', 'POST'))
    def edit_view(self):
        return self.check_access() or super().edit_view()

    @expose('/delete/', methods=('POST', ))
    def delete_view(self):
        return self.check_access() or super().delete_view()

    def on_model_change(self, form, model, is_created):
        if is_created and current_user not in model.hosts:
            model.hosts.append(current_user)
        md.db.session.commit()
Example #25
0
class GenericForm(FlaskForm):
    name = wtf.StringField(
        _l('Name'),
        validators=[wtf.validators.DataRequired()]
    )
    order_number = wtf.IntegerField(
        _l('Order Number'),
        validators=[wtf.validators.DataRequired()],
        default=1
    )
    number_of_questions = wtf.IntegerField(
        _l('Number of Questions'),
        validators=[wtf.validators.DataRequired()],
        default=10
    )
    question_text = wtf.TextAreaField(
        _l('Default Question Text'),
        validators=[wtf.validators.Optional()],
        default=None
    )
    submit = wtf.SubmitField(_l('Create Section'))

    def create(self, quiz: md.Quiz):
        section = md.Section(
            user_id=current_user.id,
            container=quiz,
            order_number=self.order_number.data,
            name=self.name.data
        )
        md.db.session.add(section)

        for i in range(self.number_of_questions.data):
            question = md.Question(
                text=self.question_text.data or _('Question %(num)s', num=i+1),
                order_number=i+1,
                container=section
            )
            md.db.session.add(question)
            md.db.session.add(md.Value(
                text=_('Answer'),
                question=question,
                allowed_misses=3,
                points=1
            ))

        return section
Example #26
0
class RegistrationForm(FlaskForm):
    email = StringField(_l(u'Email'),
                        validators=[InputRequired(),
                                    Length(1, 64),
                                    Email()])
    username = StringField(
        _l(u'Username'),
        validators=[
            InputRequired(),
            Length(1, 64),
            Regexp(
                '^[A-Za-z][A-Za-z0-9_.]*$', 0,
                _l(u'Username must have only letters, numbers, dots or underscores.'
                   ))
        ])
    password = PasswordField(_l(u'Password'),
                             validators=[InputRequired(),
                                         Length(8, 64)])
    confirmed = PasswordField(_l(u'Confirm password'),
                              validators=[
                                  InputRequired(),
                                  EqualTo('password',
                                          _l(u'Passwords must match.'))
                              ])
    submit = SubmitField(_l(u'Register'))

    def validate_email(self, field):
        if User.query.filter_by(email=field.data.lower()).first():
            raise ValidationError(_l(u'Email already registered.'))  # 邮箱已被注册。

    def validate_username(self, field):
        if User.query.filter_by(username=field.data.lower()).first():
            raise ValidationError(_l(u'Username already in use.'))  # 用户名已被使用。
Example #27
0
def query_filter(model_class, label: str = None, flt = None):
    if label is None:
        label = _l(model_class.__name__)

    if flt:
        qry = model_class.query.filter(flt)
    else:
        qry = model_class.query
    return EnumEqualFilter(model_class.id, label,
                           options=[(x.id, str(x)) for x in qry.all()])
Example #28
0
class UserView(ModelView):
    columns = {
        'username': _l('Username'),
        'email': _l('E-mail'),
        'language': _l('Language'),
        'roles': _l('Roles')
    }
    form_columns = ['username', 'email', 'password_str', 'language', 'roles']
    form_extra_fields = {
        'password_str': wtf.PasswordField(_l('Password'))
    }

    def is_accessible(self) -> bool:
        if current_user.is_authenticated:
            return current_user.has_role('admin')

    @property
    def _column_filters(self):
        # noinspection PyTypeChecker
        return [query_filter(model.User)]
Example #29
0
class WhoAmIForm(GenericForm):
    question_text = None
    number_of_questions = wtf.IntegerField(
        _l('Number of Questions'),
        validators=[wtf.validators.DataRequired()],
        default=5
    )
    answer = wtf.StringField(
        _l('Answer'),
        validators=[wtf.validators.DataRequired()]
    )
    submit = wtf.SubmitField(_l('Create Section'))

    def create(self, quiz: md.Quiz):
        section = md.Section(
            user_id=current_user.id,
            container=quiz,
            order_number=self.order_number.data,
            name=self.name.data
        )
        md.db.session.add(section)

        for i in range(self.number_of_questions.data):
            question = md.Question(
                text=_('Statement %(num)s', num=i+1),
                order_number=i+1,
                show_values=False,
                bonus=True,
                container=section
            )
            md.db.session.add(question)
            for ans in self.answer.data.split(','):
                text = ans.strip()
                md.db.session.add(md.Value(
                    text=text,
                    question=question,
                    allowed_misses=int(len(text) / 4) + 1,
                    points=self.number_of_questions.data-i
                ))

        return section
Example #30
0
def rent(id):
    qry = db.session.query(Book).filter(Book.id==id)
    book = qry.first()

    if book:
        import datetime
        if book.renter_name == current_user.username:
            book.renter_name = None
            book.rented_time = None
            db.session.commit()
        elif book.renter_name is None:
            qry = db.session.query(User).filter(User.id==current_user.id)
            user = qry.first()
            book.renter_name = user.username
            book.rented_time = datetime.datetime.now()
            db.session.commit()
        else:
            flash(_l(u'ERROR Book {title} is already rented by someone else.').format(title=book.title))
    else:
        flash(_l(u'ERROR Book #{id} doesn''t exist').format(id=id))
    return redirect(url_for('.index'))