Last active
April 12, 2017 14:52
-
-
Save stlehmann/1af2219b8067672c85c98ba187db1067 to your computer and use it in GitHub Desktop.
code for testing model inheritance with flask-admin
This file contains hidden or 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, request, redirect, url_for | |
from flask_mongoengine import MongoEngine | |
from flask_admin import Admin | |
from flask_admin.base import expose | |
from flask_admin.contrib.mongoengine import ModelView | |
from flask_admin.helpers import get_form_data | |
from flask_admin.model.helpers import get_mdict_item_or_list | |
app = Flask(__name__) | |
app.config['SECRET_KEY'] = '8e12c91677b3b3df266a770b22c82f2f' | |
app.config['MONGODB_SETTINGS'] = {'DB': 'testing'} | |
db = MongoEngine(app) | |
class User(db.Document): | |
name = db.StringField(max_length=40) | |
tags = db.ListField(db.ReferenceField('Tag')) | |
password = db.StringField(max_length=40) | |
def __str__(self): | |
return self.name | |
class Tag(db.Document): | |
name = db.StringField(max_length=10) | |
meta = {'allow_inheritance': True} | |
def __str__(self): | |
return self.name | |
class CommentedTag(Tag): | |
comment = db.StringField(max_length=180) | |
class ValueTag(Tag): | |
value = db.IntField() | |
class UserView(ModelView): | |
column_filters = ['name'] | |
column_searchable_list = ('name', 'password') | |
form_ajax_refs = { | |
'tags': { | |
'fields': ('name',) | |
} | |
} | |
class CommentedTagView(ModelView): | |
pass | |
class TagView(ModelView): | |
@expose('/edit/', methods=('GET', 'POST')) | |
def edit_view(self, *args, **kwargs): | |
id = get_mdict_item_or_list(request.args, 'id') | |
model = self.get_one(id) | |
if isinstance(model, CommentedTag): | |
return redirect(url_for('commentedtag.edit_view', id=id)) | |
elif isinstance(model, ValueTag): | |
return redirect(url_for('valuetag.edit_view', id=id)) | |
return super().edit_view(*args, **kwargs) | |
@app.route('/') | |
def index(): | |
return 'Hello World' | |
if __name__ == '__main__': | |
admin = Admin(app) | |
admin.add_view(UserView(User)) | |
admin.add_view(TagView(Tag, category='Tags')) | |
admin.add_view(ModelView(ValueTag, category='Tags')) | |
admin.add_view(CommentedTagView(CommentedTag, category='Tags')) | |
app.run(host='0.0.0.0', debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment