Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

html

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_tag'

Here are my files:

contact.html

{% extends "layout.html" %}

{% block content %}
  <h2>Contact</h2>
  <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>
{% endblock %} 

forms.py

from flask.ext.wtf import Form
from wtforms import Form, 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")

routes.py

from flask import Flask, render_template, request
from forms import ContactForm

app = Flask(__name__)
app.secret_key = 'development key'

@app.route('/')
def home():
  return render_template('home.html')

@app.route('/about')
def about():
  return render_template('about.html')

@app.route('/contact', methods=['GET', 'POST'])
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)

All the other page templates are working perfectly fine. Any advice would be awesome! Thanks for the help!

like image 368
Richard Bustos Avatar asked Oct 26 '13 21:10

Richard Bustos


1 Answers

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.

like image 200
Yuji 'Tomita' Tomita Avatar answered Oct 06 '22 22:10

Yuji 'Tomita' Tomita