【问题标题】:Issue with csrf_token while using Flask and WTForms使用 Flask 和 WTForms 时出现 csrf_token 问题
【发布时间】:2019-12-03 21:07:44
【问题描述】:

我正在尝试为我的网站设置一个基本的“联系”表单,它基本上会接收值,然后将它们放入 CSV 文件中。我遇到的问题是无法验证条目,因为它们缺少 csrf_token?

这是我的 app.py 中的相关代码:

@app.route('/contact_end', methods=['POST'])
def handle_contact():
    form = ContactForm()
    print(form.name.data)
    if form.validate_on_submit():
        print("yup")
        with open('data/messages.csv', 'a') as f:
            print("oh shit")
            writer = csv.writer(f)
            writer.writerow([form.name.data, form.email.data, form.message.data])
            print("waddup")

        return redirect(url_for('contact_handler.html'), name=form.name.data)
    print(form.errors)
    return render_template('contact.html', form=form)

它跳过 if 语句,因为它永远不会结束打印“yup”,而是打印出错误:

{'csrf_token': ['CSRF 令牌丢失。']}

这个连接的模板是:

{% extends "base_template.html" %}
    {% block title %}Contact us {% endblock %}
    {% block content %}
    <p>Feel free to use the contact form below to send us any questions you might have.</p></br>
        <form action="/contact_end" method="post">
            {{ form.csrf_token }}
            <label>Your Name <input type="text" name="name"/></label></br>
            <label>Your Email <input type="text" name="email"/></label></br>
            <label>Your Name <textarea name="message"></textarea></label></br>
            <button type="submit">Send</button>
            <button type="reset">Clear</button>
        </form>
    {% endblock %}

我尝试过使用 form.csrf_token 和 .hidden_​​tags(),但没有成功。

同样,这是 app.py 的初始部分,它首先将您带到页面,上面的部分是表单的端点:

@app.route('/contact')
def contact():
    return render_template('contact.html', form=form)

最后,这是我的 ContactForm 类:

class ContactForm(FlaskForm):
    print("yep")
    name = StringField('Name', validators=[InputRequired()])
    email = EmailField('Email', validators=[InputRequired(), Email()])
    message = TextAreaField('Message', validators=[InputRequired()])

我也确保设置了我的密钥。任何人都知道为什么这不起作用?非常感谢。

【问题讨论】:

    标签: python html flask flask-wtforms wtforms


    【解决方案1】:

    您仍然需要在 contact() 函数中创建表单实例:

    @app.route('/contact')
    def contact():
        form = ContactForm()
        return render_template('contact.html', form=form)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 2021-06-21
      • 2015-05-06
      • 2023-02-02
      • 1970-01-01
      • 2019-09-10
      相关资源
      最近更新 更多