Reputation: 57
currently i'm trying to create contact page using flask, flask-mail and flask-WTF. Message is being sent, but i only get "From: None None Random string". Could You tell me, what i'm doing wrong?
server.py:
from flask import Flask, render_template, request
from forms import ContactForm
from flask_mail import Mail, Message
mail = Mail()
app = Flask(__name__)
app.secret_key = 'developerKey'
app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 465
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = '****@gmail.com'
app.config["MAIL_PASSWORD"] = '****'
mail.init_app(app)
@app.route('/', methods=['GET', 'POST'])
def view():
return render_template('index.html')
@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()
if request.method == 'POST':
msg = Message("Portfolio", sender='[email protected]', recipients=['****@gmail.com'])
msg.body = """From: %s <%s> %s %s""" % (form.name.data, form.email.data, form.message.data, "Random string")
mail.send(msg)
return 'Form posted.'
elif request.method == 'GET':
return render_template('contact.html', form=form)
app.debug = True
if __name__ == '__main__':
app.run()
forms.py
from wtforms import Form, TextField, TextAreaField,SubmitField,validators
class ContactForm(Form):
name = TextField("Name", [validators.Required()])
email = TextField("Email", [validators.Required()])
message = TextAreaField("Message", [validators.Required()])
submit = SubmitField("Send", [validators.Required()])
contact.html
<body>
<h1>Contact Form:</h1>
<form action="/contact" method="post">
{{ form.hidden_tag }}
<p>
{{ form.name.label }}
{{ form.name }}
</p>
<p>
{{ form.email.label }}
{{ form.email }}
</p>
<p>
{{ form.message.label }}
{{ form.message }}
</p>
<p>
{{ form.submit }}
</p>
</form>
</body>
P.S. {{from.hidden.tag}} works only without bracket
Upvotes: 0
Views: 458
Reputation: 127180
The message isn't empty, the form values are. They're empty because the form isn't validating (and you're not even checking its validity). It's invalid because you're not passing the request.form
data to the form. That's not happening automatically, and hidden_tag
isn't available, because you inherited from wtforms.Form
rather than flask_wtf.Form
.
from flask_wtf import Form
class ContactForm(Form):
...
@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()
if form.validate_on_submit():
# send a message and return something
return render_template('contact.html', form=form)
Be sure to call form.hidden_tag()
in the template, since Flask-WTF's form will not validate without the hidden CSRF field.
Upvotes: 1