Skip to content

Instantly share code, notes, and snippets.

@mrjoes
Created October 3, 2012 11:07
Show Gist options
  • Save mrjoes/3826421 to your computer and use it in GitHub Desktop.
Save mrjoes/3826421 to your computer and use it in GitHub Desktop.
Child models in flask-admin edit model view
{% extends 'admin/model/edit.html' %}
{% macro table(columns, items, endpoint) %}
<table class="table table-striped table-bordered model-list">
<thead>
<tr>
<th></th>
{% for c in columns %}
<th>{{ c }}</th>
{% endfor %}
</tr>
</thead>
{% for item in items %}
<tr>
<td>
<a class="icon" href="{{ url_for(endpoint + '.edit_view', id=item.id, url=edit_url) }}"><i class="icon-pencil"></i></a>
<form class="icon" method="POST" action="{{ url_for(endpoint + '.delete_view', id=item.id, url=return_url) }}">
<button onclick="return confirm('{{ _gettext('You sure you want to delete this item?') }}');">
<i class="icon-remove"></i>
</button>
</form>
</td>
{% for c in columns %}
<td>
{{ item[c] }}
</td>
{% endfor %}
</tr>
{% endfor %}
{% endmacro %}
{% block body %}
{{ super() }}
{{ table(['id', 'name'], children, 'child') }}
{% endblock %}
from flask import Flask, request, url_for
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.admin.contrib import sqlamodel
from flask.ext import admin
# 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:///test.sqlite'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
# Create models
class Parent(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120))
def __unicode__(self):
return self.name
class Child(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode(64))
parent_id = db.Column(db.Integer(), db.ForeignKey(Parent.id))
parent = db.relationship(Parent, backref='children')
def __unicode__(self):
return self.name
# Flask views
@app.route('/')
def index():
return '<a href="/admin/">Click me to get to Admin!</a>'
# Customized Post model admin
class ParentAdmin(sqlamodel.ModelView):
edit_template = 'edit_child.html'
@admin.expose('/edit/')
def edit_view(self):
id = request.args.get('id')
children = db.session.query(Child).filter_by(parent_id=id)
self._template_args.update(dict(children=children,
edit_url=url_for('.edit_view', id=id)))
return super(ParentAdmin, self).edit_view()
if __name__ == '__main__':
# Create admin
a = admin.Admin(app, 'Simple Models')
# Add views
a.add_view(ParentAdmin(Parent, db.session))
a.add_view(sqlamodel.ModelView(Child, db.session, endpoint='child'))
# 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