zoukankan      html  css  js  c++  java
  • flask 使用宏渲染表单(包含错误信息) --

    在模板中渲染表单时,有大量的工作:

    1、调用字段属性,获取<input>定义

    2、调用对应的label属性,获取<label>定义

    3、渲染错误消息

    为了避免为每一个字段重复这些代码,我们可以创建一个宏来渲染表单字段

    macro.html:

    {% macro form_field(field) %}
        {{ field.label }}<br>
        {{ field(**kwargs) }}<br>
        {% if field.errors %}
            {% for error in field.errors %}
                <small class="error">{{ error }}</small>>
            {% endfor %}
        {% endif %}
    {% endmacro %}

    这个form_field()宏接收表单类实例的字段属性和附加的关键字参数作为输入,返回包含<label>标签、表单字段、错误消息列表的HTML类表单字段代码。使用这个宏渲染表单的示例如下所示:

    basic_macro.html:

    {% from 'macros.html' import form_field %}
    
    {% extends 'base.html' %}
    {% block content %}
        <form method="post">
            {{ form.csrf_token }}
            {{ form_field(form.name) }}<br>
            {{ form_field(form.password) }}
            {{ form.submit }}<br>
        </form>
    {% endblock %}
    app.py中加视图函数
    @app.route('/basic_macro',methods=['GET','POST'])
    def basic_macro():
        form = HelloForm()
        if form.validate_on_submit():
            username=form.name.data
            flash('welcom home, %s!' % username)
            return redirect(url_for('hello'))
        return render_template('basic_macro.html',form = form)

    访问127.0.0.1:5000/basic_macro:

    输入空格,点击提交:

    在上面的代码中,我们调用form_field()宏逐个渲染表单中的字段,只要把每一个类属性传入form_field()宏,即可完成渲染。

  • 相关阅读:
    与HDFS交互- By java API编程
    与HDFS交互- By web界面
    与HDFS交互-By shell命令
    hadoop下HDFS基本命令使用
    ubuntu安装hadoop经验
    HTTP状态码了解
    软件需求与分析
    软件需求与分析
    软件需求与分析
    浪潮之巅
  • 原文地址:https://www.cnblogs.com/xiaxiaoxu/p/10549428.html
Copyright © 2011-2022 走看看