我似乎无法让我的flask应用程序显示我的表单flask\u wtf

2024-04-20 04:44:32 发布

您现在位置:Python中文网/ 问答频道 /正文

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if request.method == 'POST':
        return render_template('contact.html',form=form)
                if form.validate_on_submit():
                      msg=Message(request.form['subject'], sender = request.form['name'],request.form['email'],
                      recepients=[request.form['email']]) 
                      msg.body='This is the body'
                      mail.send(msg)
                     flash('Message sent successfully')
                return redirect(url_for('/'))


我一直在尝试在我的烧瓶应用程序中运行一个简单的烧瓶表单,但是它无法显示表单。我一直在网上搜索,我似乎找不到我在哪里得到的错误。 这是我的html代码和form.py:

{% extends "base.html" %}
{% block main %}
{% block content %}
<h1>Contact Form</h1>
<p> Fill in this form to contact the site owners</p>
<br>
<form action= "{{url_for('/contact')}", method= "post">

    <div class="form-group">
            <label for="name"> Name</label>
            <input type="text" class="form-control" name="name" id="name"/>
    </div>
    {{form.name.label}}  {{form.name}} <br>
    <br>
   <div class="form-group">
            <label for="email">E-mail</label>
            <input type="email" class="form-control" name="email" id="email" placeholder="jdoe@example.com" />
    </div>
  {{form.email.label}}{{form.email}}<br>
    <div class="form-group">
             <label for="subject">Subject</label>
             <input type="text" class="form-control" name="subject" id="subject"/>
   </div>                                                                                 
  {{form.subject.label}}{{form.subject}}<br>
     <div class="form-group">
       <label for="message">Message</label>
       <input type="text" class="form-control" name="message" id="message"/>
   </div>

  {{form.message.label}}<br>
  {{form.message}}
  {{form.csrf_token}}


<button type ="submit">Send</button>

</form>
{% endblock %}


1条回答
网友
1楼 · 发布于 2024-04-20 04:44:32

您渲染模板太早了。请尝试:

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        msg = Message(request.form['subject'], 
                      sender=request.form['name'],
                      request.form['email'],
                      recipients=[request.form['email']]) 
        msg.body='This is the body'
        mail.send(msg)
        flash('Message sent successfully')
        return redirect(url_for('/'))
    return render_template('contact.html',form=form)

相关问题 更多 >