Skip to content

Instantly share code, notes, and snippets.

@nickretallack
Last active December 28, 2015 19:48
Show Gist options
  • Save nickretallack/7552307 to your computer and use it in GitHub Desktop.
Save nickretallack/7552307 to your computer and use it in GitHub Desktop.
Demonstrates a bug in Flask-Sqlalchemy where form rules breaks on relationships that do not already have at least one member.
Requirements: Postgresql, Flask-Admin, Flask-Sqlalchemy
How to run it:
createdb inline_bug
psql inline_bug -af schema.sql
python app.py
Go to /admin and try to edit the servers. One will work, one will not.
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://localhost:5432/inline_bug'
# Sqlalchemy Reflect
db = SQLAlchemy(app)
connection = db.engine.connect()
db.metadata.reflect(bind=db.engine)
# Models
class Haver(db.Model):
__table__ = db.metadata.tables['havers']
class Belonger(db.Model):
__table__ = db.metadata.tables['belongers']
haver = db.relationship(Haver, backref="belongers")
# Admin Views
class HaverView(ModelView):
inline_models = (Belonger,)
form_create_rules = [
'name',
'belongers'
]
form_edit_rules = form_create_rules
# Create Admin
admin = Admin(app, name="InlineBug")
admin.add_view(HaverView(Haver, db.session))
if __name__ == '__main__':
app.debug = True
app.run()
CREATE TABLE havers (
id serial primary key,
name varchar(255)
);
CREATE TABLE belongers (
id serial primary key,
haver_id serial not null references havers (id) on delete cascade,
name varchar(255)
);
insert into havers (name) values ('Works'),('Breaks');
insert into belongers (name, haver_id) select 'Belonger', id as haver_id from havers where name = 'Works';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment