如何使用SQLALCHEMY将flask-WTForm的输入打印到html

时间:2014-12-08 21:25:20

标签: flask sqlalchemy flask-sqlalchemy flask-wtforms

  

我按照教程Flask-WTF

     

现在我的问题是如何显示用户在contact.html中输入的输入,并将其显示在info.html中   用SQLALCHEMY?我使用form.populate_obj()但不知道它是否正常工作这是我迄今为止所做的事情   forms.py是相同的,我在routs.py中进行了更改,并添加了model.py和info.html

#this is routs.py
from flask import Flask, render_template, url_for, request, flash
from form import LoginForm 
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask (__name__)
app.secret_key = 'pegahpegah'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////test.db'
db = SQLAlchemy(app)

@app.route('/')
def home():
return render_template('home.html')

@app.route('/about')
def about():
return render_template('about.html')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = LoginForm()
if request.method == 'POST':
    if form.validate()== True:
    newcontact = Contact(name=form.name,
                              email=form.email,
                              subject=form.subject,
                              message=form.message)
    try:
        db.session.add(newcontact)
        db.session.commit()
        flash('Contact commited to database')
        return redirect(flask.url_for('info'))
   except:
        #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 
        flash('All fields are required.')
 return render_template('contact.html', form=form)

@app.route('/info', methods=['GET', 'POST'])
def info():
  form = LoginForm()
  contactinfo = Contact.query.first()
  #Populate the form
  form.name = contactinfo.name
  form.email = contactinfo.email
  form.subject = contactinfo.subject
  form.message = contactinfo.message
  #returns the html page, along with the form        
  return render_template('info.html', form=form)

 if __name__ == '__main__':
 app.run(debug=True)    
  

form.py

 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")
  

model.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))


   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)
  

在info.html

     {% 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 %}
  

contact.html

   {% 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 %}

当我按提交并且所有表单都有效时没有任何事情发生且它没有指向信息并且没有flash显示,如果我尝试打开info.html AttributeError

AttributeError:type object&#39; LoginForm&#39;没有属性&#39;查询&#39;

1 个答案:

答案 0 :(得分:0)

此代码有望为您提供一种有效的方法。我添加了评论,希望能够更清楚地了解正在发生的事情。

@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的表。

相关问题