【问题标题】:Flask, jinja2: Is it possible to render part of a page with render_template() without affecting the rest of the pageFlask,jinja2:是否可以使用 render_template() 渲染页面的一部分而不影响页面的其余部分
【发布时间】:2014-03-31 09:39:34
【问题描述】:

我有一个主页,其中包含几个不同的表单,其中一个是编辑个人资料表单。我正在使用 wtfforms 处理表单,并有一个名为 edit_profile.html 的子模板,它呈现原始表单和 edit_profile 视图函数返回的任何错误。我想做的是:

如果返回错误:在不影响页面其余部分的情况下呈现子模板 edit_profile.html。

目前有主页查看功能:

@app.route('/', methods=['GET','POST'])
def home():
  cur = g.db.execute(some_select_statement)
  data = cur.fetchall()
  some_var = some_function(data)
  ep_form = EditProfile()
  return render_template('home.html', some_var=some_var, ep_form=ep_form)

然后是一个处理配置文件编辑的函数:

@app.route('/edit_profile', methods=['GET', 'POST'])
def edit_profile():
  ep_form = EditProfile()
  if ep_form.validate_on_submit():
    # In here is the code that handles the new profile data
  return render_template('edit_html', ep_form=ep_form)

在返回错误的那一刻,除了利用“some_var”进行渲染的页面之外,大部分页面都被返回。我知道我可以使用 Ajax 来呈现 WTF 错误值并保持页面的其余部分不变,但我想知道是否有一种方法可以只使用 Flask 和 Jinja。

【问题讨论】:

    标签: flask jinja2 flask-wtforms


    【解决方案1】:

    如果在处理表单数据时遇到任何错误,请使用 POST 数据重定向到 home 端点(使用代码 307)。

    @app.route('/edit_profile', methods=['GET', 'POST'])
    def edit_profile():
      ep_form = EditProfile()
      if ep_form.validate_on_submit():
        # If the data is validated and good
        # In here is the code that handles the new profile data
        return render_template('edit_html', ep_form=ep_form)
      else:
        # If any errors are encountered, redirect
        # back to the home endpoint along with POST data
        # using code 307
        return redirect(url_for('home'), code=307)
    

    现在在home 端点中,我们需要处理可能从edit_profile 重定向的POST 数据。

    @app.route('/', methods=['GET','POST'])
    def home():
      # fetch data from DB, other values
      ep_form = EditProfile()
    
      # We need to call validate_on_submit so that 
      # the data is validated and errors are populated
      if request.method == "POST":
        ep_form.validate_on_submit()
    
      return render_template('home.html', some_var=some_var, ep_form=ep_form)
    

    这样,主页视图功能将可以访问表单数据,对其进行验证并显示错误。

    【讨论】:

    • 非常感谢 vivekagr 这似乎工作得很好
    猜你喜欢
    • 2014-02-26
    • 2016-06-12
    • 2011-11-28
    • 2022-01-22
    • 2019-06-20
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 2022-10-19
    相关资源
    最近更新 更多