Flask 如何使用SQLALCHEMY将输入从表单打印到html

Flask 如何使用SQLALCHEMY将输入从表单打印到html,flask,sqlalchemy,flask-sqlalchemy,flask-wtforms,Flask,Sqlalchemy,Flask Sqlalchemy,Flask Wtforms,我遵循教程 现在我的问题是如何显示用户在contact.html中输入的内容,并在info.html中显示 用炼金术?我使用form.populate_obj,但不知道它是否有效,这就是我到目前为止所做的事情 forms.py是相同的,我在routs.py和add model.py和info.html中进行了更改 form.py model.py info.html contact.html 当我按submit,所有表单都有效时,不会发生任何事情,也不会指向信息,也不会显示flash,如果我尝试

我遵循教程

现在我的问题是如何显示用户在contact.html中输入的内容,并在info.html中显示 用炼金术?我使用form.populate_obj,但不知道它是否有效,这就是我到目前为止所做的事情 forms.py是相同的,我在routs.py和add model.py和info.html中进行了更改

form.py

model.py

info.html

contact.html

当我按submit,所有表单都有效时,不会发生任何事情,也不会指向信息,也不会显示flash,如果我尝试打开info.html AttributeError


AttributeError:type对象“LoginForm”没有属性“query”

此代码有望为您提供一种工作方法。我添加了一些评论,希望能让事情变得更清楚

@app.route('/contact', methods=['GET', 'POST'])
def contact():
   form = ContactForm()
   print('ContactForm created')
   if request.method == 'POST':
      print('Entered Post')
      if form.validate_on_submit:  #If the form contains all required fields
         print('Form validated')
         #Create a new contact and commit it to the db.
         newcontact = Contact(name=form.name.data,
                              email=form.email.data,
                              subject=form.subject.data,
                              message=form.message.data)
         try:
            print('Trying to add newcontact')
            db.session.add(newcontact)
            print('contact added')
            db.session.commit()
            print('contact commited')
            flash('Contact commited to database')
            return redirect(flask.url_for('info')) 
         except:
            print('Exception')
            #Something went wrong when trying to add to the database.
            flash('Could not commit new contact') 
      else: #If the form does not have all fields that are required 
         print('Entered else')
         flash('All fields are required.')
   print('Return')
   return render_template('contact.html', form=form)

 @app.route('/info', methods=['GET', 'POST'])
 def info():
    form = ContactForm()
    #Fetch the first contact from db.
    contactinfo = Contact.query.first()
    #if you want to fetch a specific contact you need to specify it like this,
    #contactinfo = Contact.query.filter_by(name='somenamehere').first()

    #Populate the form
    form.name.data = contactinfo.name
    form.email.data = contactinfo.email
    form.subject.data = contactinfo.subject
    form.message.data = contactinfo.message
    #returns the html page, along with the form        
    return render_template('info.html', form=form)

{% extends "layout.html" %}
  {% block content %}
     <h2>show the info</h2>
        {% for entry in form %}
           <strong>name:</strong> {{ entry.name}} <br>
           <strong>email:</strong> {{ entry.email }} <br>
           <strong>subject</strong> {{ entry.subject }} <br>
           <strong>messaget</strong> {{ entry.message }} <br>
          <br>
        {% endfor %}
  {% endblock %}

---forms.py--
from flask_wtf import Form
from wtforms import StringField
from wtforms.validators import DataRequired

class ContactForm(Form):
    name = StringField('name', validators=[DataRequired()])
    email = StringField('email', validators=[DataRequired()])
    subject = StringField('subject', validators=[DataRequired()])
    message = StringField('message', validators=[DataRequired()])

--models.py--
from flask.ext.sqlalchemy import SQLAlchemy
from routs import db

class Contact(db.Model):
   __tablename__ = "Contact"
   id = db.Column(db.Integer, primary_key = True)
   name = db.Column(db.String(50))
   email = db.Column(db.String(50))
   subject = db.Column(db.String(50))
   message = db.Column(db.String(50))
在html中,我们将循环遍历表单中获得的数据,并为每个条目打印信息。注意:在我的示例中,您将始终从数据库中提取第一个contactinfo,因此将始终获得相同的联系人,并且只有一个联系人

编辑: 在forms.py中,我们创建了一个将在联系人页面中使用的表单。表单定义了表单的必要字段和结构。
在models.py中,我们定义了一个模型,表示数据库中的联系人条目。这意味着您的数据库中必须有一个名为Contact的表。

请更正代码我确信我遗漏了很多……没有人会为您调试所有代码,这不是stackoverflow的内容。请清楚地提出一个您正在努力解决的问题,而不是所有的代码,除非每个可能阅读该问题的人都特别感兴趣。你应该正确地定义你想要达到的目标,以及你被困在哪里。在我看来,aIt需要对代码有一个基本的了解。在您的联系人中,您没有对表单执行任何操作,您可能应该将其存储到数据库中。在应该从数据库读取的信息中,使用收到的信息填充表单,然后将其显示给用户。在发布问题之前,您应该格式化您的代码。@Zyber@GG_Python Thanx对于您的评论,我很难理解这段代码,如果您能帮助我,我将不胜感激,我编辑代码,我对我认为可能存在问题的部分添加了注释。我想我应该在routs.py中导入联系人,否则将是错误名称错误:未定义全局名称“联系人”,但我像routs.py顶部的模型导入*一样进行了排序,但是ImportError:无法导入姓名联系人,因此我将其放在db=SQLAlchemyapp之后再次无效,如果我尝试打开info.html error bold sqlalchemy.exc.InvalidRequestError@Zyber–Thanx以寻求您的帮助@ZyberFinally,我可以创建数据库并将表连接到数据库,但现在flash仍然不起作用,它不会将其指向info.html,当我打开info.html AttributeError:'NoneType'对象没有属性'name'form.name=contactinfo.name你能帮我吗@Zyber当您尝试打开info.html时,会出现属性错误。这意味着您没有从数据库查询中获得任何信息,它无法在数据库中找到联系人。我猜这是因为当您试图将联系人添加到contact.html中的数据库时,没有成功。对于您的第一个错误,很难判断问题是什么,因为您没有提供任何直接信息。尝试添加一些指纹以了解发生了什么。我们需要找出导致问题的行。检查我编辑的代码@Pegasuss确保您使用的是信息和联系人中正确位置的数据。与我的代码进行比较,并进行必要的更改,使其看起来像我的代码。如果不起作用,请在问题中输入当前代码@百合白
 from flask.ext.wtf import Form
 from wtforms import StringField, SubmitField, validators, ValidationError
 from wtforms.validators import DataRequired

 class LoginForm(Form):
     name = StringField("Name", [validators.Required("Please enter your name.")])
     email = StringField("Email", 
     [validators.Required("Please enter your email  address."),
     validators.Email("Please enter valid email address.")])
     subject = StringField("Subject", 
     [validators.Required("Please enter your subject.")])
     message = StringField("Message", 
     [validators.Required("Please enter your  message.")])
     submit = SubmitField("Submit")
from flask.ext.sqlalchemy import SQLAlchemy
from routs import db


class Contact(db.Model):
  __tablename__ = "Contact"
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(50))
    email = db.Column(db.String(50))
    subject = db.Column(db.String(50))
    message = db.Column(db.String(50))


   def __init__(self, name, email, subject, ):
       self.name = name
       self.email = email
       self.subject = subject
       self.message = message

   def __repr__(self):
       return '<ContactForm %r>' % (self.message)
     {% extends "layout.html" %}
     {% block content %}
    <h2>show the info</h2>
      {% for entry in form %}
         <strong>name:</strong> {{ entry.name}} <br>
         <strong>email:</strong> {{ entry.email }} <br>
         <strong>subject</strong> {{ entry.subject }} <br>
         <strong>messaget</strong> {{ entry.message }} <br>
        <br>
       {% endfor %}
  {% endblock %}
   {% extends "layout.html" %}
   {% block content %}
   <h2>Contact</h2>

   {% for message in form.name.errors %}
   <div class="flash">{{ message }}</div>
   {% endfor %}

   {% for message in form.email.errors %}
   <div class="flash">{{ message }}</div>
   {% endfor %}

   {% for message in form.subject.errors %}
   <div class="flash">{{ message }}</div>
   {% endfor %}

   {% for message in form.message.errors %}
    <div class="flash">{{ message }}</div>
   {% endfor %}

  <form action="{{url_for('contact')}}" method=post>
    {{ form.hidden_tag() }}

    {{ form.name.label }}
    {{ form.name }}

    {{ form.email.label }}
    {{ form.email }}

    {{ form.subject.label }}
    {{ form.subject }}

    {{ form.message.label }}
    {{ form.message}}

    {{form.submit}}
  </form>  

 {% endblock %}
@app.route('/contact', methods=['GET', 'POST'])
def contact():
   form = ContactForm()
   print('ContactForm created')
   if request.method == 'POST':
      print('Entered Post')
      if form.validate_on_submit:  #If the form contains all required fields
         print('Form validated')
         #Create a new contact and commit it to the db.
         newcontact = Contact(name=form.name.data,
                              email=form.email.data,
                              subject=form.subject.data,
                              message=form.message.data)
         try:
            print('Trying to add newcontact')
            db.session.add(newcontact)
            print('contact added')
            db.session.commit()
            print('contact commited')
            flash('Contact commited to database')
            return redirect(flask.url_for('info')) 
         except:
            print('Exception')
            #Something went wrong when trying to add to the database.
            flash('Could not commit new contact') 
      else: #If the form does not have all fields that are required 
         print('Entered else')
         flash('All fields are required.')
   print('Return')
   return render_template('contact.html', form=form)

 @app.route('/info', methods=['GET', 'POST'])
 def info():
    form = ContactForm()
    #Fetch the first contact from db.
    contactinfo = Contact.query.first()
    #if you want to fetch a specific contact you need to specify it like this,
    #contactinfo = Contact.query.filter_by(name='somenamehere').first()

    #Populate the form
    form.name.data = contactinfo.name
    form.email.data = contactinfo.email
    form.subject.data = contactinfo.subject
    form.message.data = contactinfo.message
    #returns the html page, along with the form        
    return render_template('info.html', form=form)

{% extends "layout.html" %}
  {% block content %}
     <h2>show the info</h2>
        {% for entry in form %}
           <strong>name:</strong> {{ entry.name}} <br>
           <strong>email:</strong> {{ entry.email }} <br>
           <strong>subject</strong> {{ entry.subject }} <br>
           <strong>messaget</strong> {{ entry.message }} <br>
          <br>
        {% endfor %}
  {% endblock %}

---forms.py--
from flask_wtf import Form
from wtforms import StringField
from wtforms.validators import DataRequired

class ContactForm(Form):
    name = StringField('name', validators=[DataRequired()])
    email = StringField('email', validators=[DataRequired()])
    subject = StringField('subject', validators=[DataRequired()])
    message = StringField('message', validators=[DataRequired()])

--models.py--
from flask.ext.sqlalchemy import SQLAlchemy
from routs import db

class Contact(db.Model):
   __tablename__ = "Contact"
   id = db.Column(db.Integer, primary_key = True)
   name = db.Column(db.String(50))
   email = db.Column(db.String(50))
   subject = db.Column(db.String(50))
   message = db.Column(db.String(50))