0

目前我正在尝试使用flask、flask-mail 和flask-WTF 创建联系页面。正在发送消息,但我只收到“发件人:无无随机字符串”。你能告诉我,我做错了什么吗?

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='contact@example.com', 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>

PS {{from.hidden.tag}} 仅在没有括号的情况下有效

4

1 回答 1

1

消息不是空的,表单值是。它们是空的,因为表单没有验证(你甚至没有检查它的有效性)。这是无效的,因为您没有将request.form数据传递给表单。这不会自动发生,hidden_tag也不可用,因为您继承自wtforms.Form而不是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)

一定要调用form.hidden_tag()模板,因为没有隐藏的 CSRF 字段,Flask-WTF 的表单将无法验证。

于 2015-10-27T18:50:32.600 回答