librelist archives

« back to archive

Fwd: Flask-sqlalchemy Flask

Fwd: Flask-sqlalchemy Flask

From:
peg kh
Date:
2014-12-11 @ 15:08
Hi I had hard time for coding this with flask,flask-sqlalchemy and
flask-wtform and I got an error I have a try to save wtform to sqlalchemy
and then display the database in info.html But when I submit it the flash
comment

flash('Contact commited to database')doesn't show and also it won't
directto info and also in if try to open info after
submit form
http://127.0.0.1:5000/info I got an error

sqlalchemy.exc.InvalidRequestError

InvalidRequestError: This Session's transaction has been rolled back due to
a previous exception during flush. To begin a new transaction with this
Session, first issue Session.rollback(). Original exception was:
(OperationalError) no such table: Contact u'INSERT INTO "Contact" (name,
email, subject, message) VALUES (?, ?, ?, ?)'
(<wtforms.fields.core.StringField object at 0x7f194c467b50>,
<wtforms.fields.core.StringField object at 0x7f194c467c10>,
<wtforms.fields.core.StringField object at 0x7f194c467910>,
<wtforms.fields.core.StringField object at 0x7f194c467850>)

routs.py

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

app = Flask (__name__)
app.secret_key = 'pegahpegah'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////test.db'#I kinda
thing here is the problem coz there is no test.db in folder
db = SQLAlchemy(app)
from model import * # to import contact tabel here

@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')# it doesn't show this
flash when everything is fine
        return redirect(flask.url_for('info'))# it doesn't direct to info.html
   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 %}


 Please help, Thanx Peg

Re: [flask] Fwd: Flask-sqlalchemy Flask

From:
Jeremy Dagorn
Date:
2014-12-11 @ 15:28
Seems to be database related: Original exception was: (OperationalError) no
such table: Contact u'INSERT INTO "Contact" (name, email, subject, message)
VALUES (?, ?, ?, ?)'
Verify that you Contact table exist.


On Thu, Dec 11, 2014 at 7:08 AM, peg kh <peg1988.kh@gmail.com> wrote:

>
> Hi I had hard time for coding this with flask,flask-sqlalchemy and
> flask-wtform and I got an error I have a try to save wtform to sqlalchemy
> and then display the database in info.html But when I submit it the flash
> comment
>
> flash('Contact commited to database')doesn't show and also it won't 
directto info and also in if try to open info after
> submit form
> http://127.0.0.1:5000/info I got an error
>
> sqlalchemy.exc.InvalidRequestError
>
> InvalidRequestError: This Session's transaction has been rolled back due
> to a previous exception during flush. To begin a new transaction with this
> Session, first issue Session.rollback(). Original exception was:
> (OperationalError) no such table: Contact u'INSERT INTO "Contact" (name,
> email, subject, message) VALUES (?, ?, ?, ?)'
> (<wtforms.fields.core.StringField object at 0x7f194c467b50>,
> <wtforms.fields.core.StringField object at 0x7f194c467c10>,
> <wtforms.fields.core.StringField object at 0x7f194c467910>,
> <wtforms.fields.core.StringField object at 0x7f194c467850>)
>
> routs.py
>
> #this is routs.pyfrom flask import Flask, render_template, url_for, 
request, flashfrom form import LoginForm from flask.ext.sqlalchemy import 
SQLAlchemy
>
> app = Flask (__name__)
> app.secret_key = 'pegahpegah'
> app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////test.db'#I kinda 
thing here is the problem coz there is no test.db in folder
> db = SQLAlchemy(app)
> from model import * # to import contact tabel here
>
> @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')# it doesn't show this 
flash when everything is fine
>         return redirect(flask.url_for('info'))# it doesn't direct to info.html
>    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 %}
>
>
>  Please help, Thanx Peg
>
>
>


-- 
Jérémy Dagorn
www.jeremydagorn.com

Android apps I developed:
https://play.google.com/store/apps/developer?id=JumyApps

Re: [flask] Fwd: Flask-sqlalchemy Flask

From:
peg kh
Date:
2014-12-11 @ 16:13
Thanx jeremy, for your reply, I had hard time with this code unfortunately
:(
I solve the error in except: I change db.session to db.session.rollback()
so it fix this error But the problem is that I couldn't see the flash
comment for none of the try part and none for except and about the tabel in
model.py when I run model.py I got error
sqlalchemy.exc.InvalidRequestError: Table 'Contact' is already defined for
this MetaData instance.  Specify 'extend_existing=True' to redefine options
and columns on an existing Table object.
and in routs.py I have app.config['SQLALCHEMY_DATABASE_URL'] =
'sqlite:///test.db' but can't see test.db in folder
I'll appreciate if u could help me out?

On Thu, Dec 11, 2014 at 5:28 PM, Jeremy Dagorn <jeremy.dagorn@gmail.com>
wrote:

> Seems to be database related: Original exception was: (OperationalError)
> no such table: Contact u'INSERT INTO "Contact" (name, email, subject,
> message) VALUES (?, ?, ?, ?)'
> Verify that you Contact table exist.
>
>
> On Thu, Dec 11, 2014 at 7:08 AM, peg kh <peg1988.kh@gmail.com> wrote:
>
>>
>> Hi I had hard time for coding this with flask,flask-sqlalchemy and
>> flask-wtform and I got an error I have a try to save wtform to
>> sqlalchemy and then display the database in info.html But when I submit it
>> the flash comment
>>
>> flash('Contact commited to database')doesn't show and also it won't 
directto info and also in if try to open info after
>> submit form
>> http://127.0.0.1:5000/info <http://%20127.0.0.1:5000/info> I got an error
>>
>> sqlalchemy.exc.InvalidRequestError
>>
>> InvalidRequestError: This Session's transaction has been rolled back due
>> to a previous exception during flush. To begin a new transaction with this
>> Session, first issue Session.rollback(). Original exception was:
>> (OperationalError) no such table: Contact u'INSERT INTO "Contact" (name,
>> email, subject, message) VALUES (?, ?, ?, ?)'
>> (<wtforms.fields.core.StringField object at 0x7f194c467b50>,
>> <wtforms.fields.core.StringField object at 0x7f194c467c10>,
>> <wtforms.fields.core.StringField object at 0x7f194c467910>,
>> <wtforms.fields.core.StringField object at 0x7f194c467850>)
>>
>> routs.py
>>
>> #this is routs.pyfrom flask import Flask, render_template, url_for, 
request, flashfrom form import LoginForm from flask.ext.sqlalchemy import 
SQLAlchemy
>>
>> app = Flask (__name__)
>> app.secret_key = 'pegahpegah'
>> app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////test.db'#I kinda 
thing here is the problem coz there is no test.db in folder
>> db = SQLAlchemy(app)
>> from model import * # to import contact tabel here
>>
>> @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')# it doesn't show this 
flash when everything is fine
>>         return redirect(flask.url_for('info'))# it doesn't direct to info.html
>>    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 %}
>>
>>
>>  Please help, Thanx Peg
>>
>>
>>
>
>
> --
> Jérémy Dagorn
> www.jeremydagorn.com
>
> Android apps I developed:
> https://play.google.com/store/apps/developer?id=JumyApps
>