I am using flask to send emails to user who submits a form in a contact page.
I have tried to test it myself but even If i fill the whole form. Every time I hit submit, I get a validation error saying that I must fill in the form. In my log it says I get a 200, which means the post was a success.
Here is the code:
routes.py
from flask import Flask, render_template, request, flash
from forms import ContactForm
from flask.ext.mail import Message, Mail
mail = Mail()
app = Flask(__name__)
app.secret_key = 'development key'
app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 465
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = 'contact@gmail.com'
app.config["MAIL_PASSWORD"] = '*********'
mail.init_app(app)
app = Flask(__name__)
app.secret_key = 'development key'
@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()
if request.method == 'POST':
if form.validate() == False:
flash('All fields are required.')
return render_template('contact.html', form=form)
else:
msg = Message(form.subject.data, sender="contact@gmail.com")
msg.body = """
From: %s <%s>
%s
""" % (form.name.data, form.email.data, form.message.data)
mail.send(msg)
return 'Form posted.'
elif request.method == 'GET':
return render_template('contact.html', form=form)
Forms.py
from flask.ext.wtf import Form
from wtforms import Form, TextField, TextAreaField, SubmitField, validators, ValidationError
class ContactForm(Form):
name = TextField("Name", [validators.Required("Please Enter Your Name")])
email = TextField("Email",[validators.Required("Please enter your email address"), validators.email("Please enter your email address")])
subject = TextField("Subject", [validators.Required("Please enter a subject.")])
message = TextAreaField("Message", [validators.Required("Please enter a message.")])
submit = SubmitField("Send")