Created
October 5, 2012 18:26
-
-
Save plaes/3841527 to your computer and use it in GitHub Desktop.
Flask-Admin InlineForm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
from flask.ext.sqlalchemy import SQLAlchemy | |
from flask.ext import admin | |
from flask.ext.admin.contrib import sqlamodel | |
from flask.ext.admin.model import InlineFormAdmin | |
# Create application | |
app = Flask(__name__) | |
# Create dummy secrey key so we can use sessions | |
app.config['SECRET_KEY'] = '123456790' | |
# Create in-memory database | |
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///xtest.sqlite' | |
db = SQLAlchemy(app) | |
# Create models | |
class Product(db.Model): | |
__tablename__ = 'products' | |
id = db.Column(db.Integer, primary_key=True) | |
description = db.Column(db.String(120), unique=True) | |
# Required for administrative interface | |
def __unicode__(self): | |
return self.description | |
class Sale(db.Model): | |
__tablename__ = 'sales' | |
id = db.Column(db.Integer, primary_key=True) | |
created_on = db.Column(db.DateTime) | |
description = db.Column(db.String(120), unique=True) | |
items = db.relationship('SaleItem', cascade='all, delete-orphan', backref='cart') | |
class SaleItem(db.Model): | |
sale_id = db.Column(db.Integer, db.ForeignKey('sales.id'), primary_key=True) | |
product_id = db.Column(db.Integer, db.ForeignKey('products.id'), primary_key=True) | |
amount = db.Column(db.Integer, nullable=False) | |
sell_price = db.Column(db.Numeric, nullable=False) | |
product = db.relationship('Product') | |
# Flask views | |
@app.route('/') | |
def index(): | |
return '<a href="/admin/">Click me to get to Admin!</a>' | |
class ProductAdmin(sqlamodel.ModelView): | |
pass | |
class SaleAdmin(sqlamodel.ModelView): | |
inline_models = (SaleItem,) | |
if __name__ == '__main__': | |
# Create admin | |
admin = admin.Admin(app, 'Simple Models') | |
# Add views | |
admin.add_view(ProductAdmin(Product, db.session)) | |
admin.add_view(SaleAdmin(Sale, db.session)) | |
# Create DB | |
db.create_all() | |
# Start app | |
app.debug = True | |
app.run('0.0.0.0', 8000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment