Question

I create a contact form in Flask, but it's not working. It gives the error NameError: global name 'ContactForm' is not defined

The custom form is :

<form action="{{ url_for('contact') }}" method=post>
    {{ form.hidden_tag() }}

    {{ form.name.label }}
    {{ form.name }}

    {{ form.email.label }}
    {{ form.email }}

    {{ form.subject.label }}
    {{ form.subject }}

    {{ form.message.label }}
    {{ form.message }}

    {{ form.submit }}
  </form>

routes.py is:

from flask import Flask, render_template
from forms import ContactForm
app = Flask(__name__)     

def contact():
    form = ContactForm()

    if request.method == 'POST':
        return 'Form posted.'

    elif request.method == 'GET':
        return render_template('contact.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)

How may I resolve the problem?

Was it helpful?

Solution

Create a new file called forms.py and insert the below code in there. Then your code should work.

from flask.ext.wtf import Form

from wtforms import TextField, TextAreaField, SubmitField, validators


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")

OTHER TIPS

firstly , do you have flask-wtf installed ?
and try this : form = ContactForm(request.form)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top