如果forms.py中的方法中的If语句未处理

问题描述 投票:1回答:1

我在使此验证生效时遇到了一些麻烦。我希望表单仅在我提交的URL末尾有有效的.yaml,.yml或.json时提交。

forms.py:

class TemplateForm(FlaskForm):
    template_url = URLField( 'Template URL', validators=[InputRequired(), URL(message='error')])
    submit = SubmitField('Add Template')

    def validate_filetype(self, field):
        form = TemplateForm
        template_path = form.template_url
        ext = os.path.splitext(template_path)[1]

        if ext not in ('.json', '.yml', '.yaml'):
            raise ValidationError('Invalid File Type')

views.py:

@apps.route('/new-template', methods=['GET', 'POST'])
@login_required
@admin_required

    def new_template():
        """Add a new app."""
        form = TemplateForm()

        if form.validate_on_submit():
            template_location = form.template_url.data
            flash("added template: " + template_location)
            template_path = urlparse(template_location).path
            ext = os.path.splitext(template_path)[1]
            flash("Extension = " + ext )
            if ext == '.json':
                flash('var = .json')
                template_filename = wget.download(template_location, out='app/storage/templates/json')
                flash(template_filename)
            elif ext in ('.yml', '.yaml'):
                flash('var = .yaml')

            return redirect(url_for('apps.index'))
        return render_template('apps/new_template.html', form=form)

new_index.html:

{% extends 'layouts/base.html' %}
{% import 'macros/form_macros.html' as f %}
{% import 'macros/check_password.html' as check %}

{% block scripts %}
{% endblock %}

{% block content %}
    <div class="ui stackable centered grid container">
        <div class="twelve wide column">
            <a class="ui basic compact button" href="{{ url_for('apps.index') }}">
                <i class="caret left icon"></i>
                Back to dashboard
            </a>
            <h2 class="ui header">
                New App Template
                <div class="sub header">Add a new app template</div>
                {% set flashes = {
                    'error':   get_flashed_messages(category_filter=['form-error']),
                    'warning': get_flashed_messages(category_filter=['form-check-email']),
                    'info':    get_flashed_messages(category_filter=['form-info']),
                    'success': get_flashed_messages(category_filter=['form-success'])
                } %}

                {{ f.begin_form(form, flashes) }}

                    {{ f.render_form_field(form.template_url, extra_classes=novalidate) }}
                    {{ f.render_form_field(form.submit) }}

                {{ f.end_form() }}
            </h2>
        </div>
    </div>
{% endblock %}

无论我做什么,我都无法使raise ValidationError('Invalid File Type')工作。我正在尝试仅使用https://test.com,并且不会抛出验证错误。

请让我知道是否还有其他应提供的信息。一切都正确导入,因此我可以确定这不是依赖性问题。

这是我正在使用的样板:https://github.com/hack4impact/flask-base

python-3.x flask flask-wtforms
1个回答
0
投票

此解决。谢谢@ ngShravil.py,我需要使用自定义验证器并将其分成自己的方法(在类外部)。

def validate_filetype(form, field):
    template_path = field.data
    ext = os.path.splitext(template_path)[1]
    if ext not in ('.json', '.yml', '.yaml'):
        raise ValidationError('Invalid File Type')

class TemplateForm(FlaskForm):
    template_url = URLField( 'Template URL', validators=[InputRequired(), URL(message='error'), validate_filetype])
    submit = SubmitField('Add Template')
© www.soinside.com 2019 - 2024. All rights reserved.