'forms.ContactForm object' has no attribute 'hidden_tag'

前端 未结 4 2057
孤街浪徒
孤街浪徒 2021-02-13 05:53

I am trying to create a contact form using flask but keep getting this error when the page is rendered.

\'forms.ContactForm object\' has no attribute \'hidden_         


        
相关标签:
4条回答
  • 2021-02-13 06:05

    The error that you're seeing is telling you that forms.ContactForm has no method called "hidden_tag". You're referencing that method on the 6th line of contact.html like this:

    {{ form.hidden_tag() }}
    

    According to the flask documentation, this is the correct way to implement CSRF protection.

    I would start by removing the line that references "form.hidden_tag()", then see if your form works. Then go back and implement CSRF protection per those instructions from the documentation.

    0 讨论(0)
  • 2021-02-13 06:15

    It took me some time to fix this.

    First import Form, fields, bootstrap as:

    from flask_wtf import Form
    from wtforms import StringField #etc
    from flask_bootstrap import Bootstrap
    

    Config secret key and bootstrap

    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret key'
    Bootstrap(app)
    

    create your form as your used to:

    class ContactForm(Form):
      name = TextField("Name", [validators.Required()])
      email = TextField("Email",[validators.Required(), validators.email()])
      subject = TextField("Subject", [validators.Required()])
      message = TextAreaField("Message", [validators.Required()])
      submit = SubmitField("Send")
    

    Nothing special in the routing aswell, just return it normaly.

    In the html:

    {% extends "bootstrap/base.html" %}
    {% import "bootstrap/wtf.html" as wtf %}
        {% if form %}
            {{ wtf.quick_form(form, ) }}
        {% endif %}
    

    And that's it. Hope you find some (or all) of it useful.

    0 讨论(0)
  • 2021-02-13 06:16

    I just fixed this problem as well.

    Your problem is that you imported Form twice, rendering your flask-wtf Form import useless.

    from flask_wtf import Form
    from wtforms import Form, TextField, TextAreaField, SubmitField, validators
    #                   ^^^ Remove
    

    Only the flask-wtf extension has the special Form class which can handle CSRF automatically / other stuff.

    0 讨论(0)
  • 2021-02-13 06:20
    I tried to fix this, too. After removing brackets "()" appended after hidden_tag, it works.

    {{ form.hidden_tag }}

    0 讨论(0)
提交回复
热议问题