首页 > 解决方案 > Flask WTForms:提交后如何刷新页面

问题描述

我有一个显示预订信息列表的页面。有一个侧边栏,用户可以使用它来过滤特定的预订。一个元素是一个多复选框表单,用户可以在其中选择多个教室。

用户提交表单后,会生成一个包含新过滤器信息的 URL,并重定向到该 URL。

形式:

class MultiCheckboxForm(SelectMultipleField):
    widget = ListWidget(prefix_label=False)
    option_widget = CheckboxInput()

class classroomSidebarForm(FlaskForm):
    classrooms_list = MultiCheckboxForm('Classrooms', coerce=int)
    submit = SubmitField('Submit selection')

蓝图:

@resblueprint.route('/<resfilter:res_filter>/', defaults={'page': 1},
                    methods=['GET', 'POST'])
@resblueprint.route('/<resfilter:res_filter>/<int:page>')
def allreservations(res_filter, page):
    '''Display reservations'''

    # code to generate other template parameters

    # code to dynamically generate the choices: classrooms_list

    form = classroomSidebarForm()
    form.classrooms_list.choices = classrooms_list

    if request.method == 'POST':
        selected_classrooms = () 

        if form.classrooms_list.data is not None:
            for selected_classroom_id in form.classrooms_list.data:
                selected_classrooms.append(
                    dict(form.classrooms_list.choices).selected_classroom_id)

        newconds = (res_filter.conds[0], res_filter.conds[1], selected_classrooms, 
                    res_filter.conds[3], res_filter.conds[4], res_filter.conds[5])
        res_filter.conds = newconds
        # the above updates the reservation filter
        # where conds[2] is replaced by the updated list of classrooms

        # then the same page should be rendered again, with the updated res_filter
        # preferably the form is not cleared

    return render_template('reservation/allres.html.j2',
                           res=res,
                           pagination=pagination,
                           res_filter=res_filter,
                           form=form)

侧边栏:

{% macro desktop_sidebar_res(endpoint, res_filter, form) %}
<div id="sidebar" class="col-md-2">

    # generates the other filter options

    <form action="{{ url_for(endpoint, res_filter=res_filter.to_url()) }}" method="POST">
        {{ form.csrf_token }}
        {{ form.classrooms_list.label }} {{ form.classrooms_list }}
        {{ form.submit }}
    </form>

    {{ caller and caller() }}
</div>
{% endmacro %}

可以确认url_for(endpoint, res_filter=res_filter.to_url())用当前过滤器信息正确地产生了当前URL。

代码无法将表单数据返回给蓝图函数。if request.method == 'POST':无法到达之后的块。所以我怀疑可能有什么问题action=""

生成新过滤器后。我将如何重新加载模板?

告诉我是否需要进一步澄清。

标签: pythonhtmlflaskflask-wtforms

解决方案


推荐阅读