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 = CurrencyFormjust 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 whatformrefers 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
()toCurrencyFormcreates a live instance of your form, complete with all the fields and methods you defined in the class. - Including
form=formin therender_templatecall makes the form object available to your Jinja2 template, so lines like{{ form.csrf_token }}and{{ render_field(form.currency_1) }}can find theformvariable they need.
Quick Additional Checks
- Double-check that your
CurrencyFormclass is properly imported inapp.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
相关产品推荐
相关产品推荐

