Skip to content

Commit

Permalink
Merge pull request #3 from pawl/add_example
Browse files Browse the repository at this point in the history
add flask example
  • Loading branch information
pawl committed Mar 26, 2016
2 parents cf1c2f6 + ad95031 commit a3056a2
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
21 changes: 21 additions & 0 deletions examples/flask/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
WTForms-SQLAlchemy + Flask examples.

To run this example:

1. Clone the repository::

git clone https://github.com/wtforms/wtforms-sqlalchemy.git
cd wtforms-sqlalchemy

2. Create and activate a virtual environment::

virtualenv env
source env/bin/activate

3. Install requirements::

pip install -r 'examples/flask/requirements.txt'

4. Run the application::

python examples/flask/basic.py
47 changes: 47 additions & 0 deletions examples/flask/basic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy

from wtforms_sqlalchemy.orm import model_form

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sample_db.sqlite'
app.config['SQLALCHEMY_ECHO'] = True

db = SQLAlchemy(app)


class Car(db.Model):
__tablename__ = 'cars'
id = db.Column(db.Integer, primary_key=True)
make = db.Column(db.String(50))
model = db.Column(db.String(50))

def __unicode__(self):
return self.name


CarForm = model_form(Car)


@app.route('/', methods=['GET', 'POST'])
def create_car():
car = Car()
success = False

if request.method == 'POST':
form = CarForm(request.form, obj=car)
if form.validate():
form.populate_obj(car)
db.session.add(car)
db.session.commit()
success = True
else:
form = CarForm(obj=car)

return render_template('create.html', form=form, success=success)


if __name__ == '__main__':
db.create_all()

app.run(debug=True)
18 changes: 18 additions & 0 deletions examples/flask/templates/create.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Create Form</title>
</head>
<body>
{% block body %}
{% if success %}<p>Saved Successfully!</p>{% endif %}
<form method="post" action="">
{% for field in form %}
<p>{{ field.label }} {{ field }}</p>
{% endfor %}
<p><button type="submit">Submit</button></p>
</form>
{% endblock %}
</body>
</html>

0 comments on commit a3056a2

Please sign in to comment.