Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add flask example #3

Merged
merged 1 commit into from
Mar 26, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>