You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask中jinja2.exceptions.UndefinedError: 'form'未定义问题求助

Fixing jinja2.exceptions.UndefinedError: 'form' is undefined in Flask

Hey there! Let's work through this Jinja2 error you're hitting— it boils down to two small but crucial missteps in your Flask route code. Let's break it down and fix it step by step.

The Root Causes

  • You didn't create an instance of your form class: In your code, form = CurrencyForm just assigns the class itself to the variable, not a usable form object. You need to add parentheses to instantiate it: form = CurrencyForm().
  • You didn't pass the form to your template: When calling render_template, you have to explicitly send the form object to your HTML template— otherwise Jinja2 has no idea what form refers to.

Modified app.py Snippet

Here's how to adjust your route to fix both issues:

@app.route("/form", methods=["GET", "POST"])
def forms():
    global reverse_exchange_rate, exchange_rate
    # 1. Create an instance of the CurrencyForm class
    form = CurrencyForm()
    if request.method == 'GET':
        # 2. Pass the form instance to the template so Jinja2 can access it
        return render_template("form.html", form=form)
    # Optional: Add POST request handling if you need to process form submissions later
    # elif request.method == 'POST':
    #     if form.validate_on_submit():
    #         # Process your form data here
    #         return redirect('/success-page')

Why This Fix Works

  • Adding () to CurrencyForm creates a live instance of your form, complete with all the fields and methods you defined in the class.
  • Including form=form in the render_template call makes the form object available to your Jinja2 template, so lines like {{ form.csrf_token }} and {{ render_field(form.currency_1) }} can find the form variable they need.

Quick Additional Checks

  • Double-check that your CurrencyForm class is properly imported in app.py (you didn't include that snippet, but it's a common easy-to-miss detail!)
  • Confirm your template file structure is still correct (you mentioned it was, but a quick sanity check never hurts)

内容的提问来源于stack exchange,提问作者Maxim O

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 15:17:48