Skip to content

Instantly share code, notes, and snippets.

@sn1p3r46
Created June 19, 2018 01:04
Show Gist options
  • Save sn1p3r46/309558e8ae440980a2f505a53fd0e855 to your computer and use it in GitHub Desktop.
Save sn1p3r46/309558e8ae440980a2f505a53fd0e855 to your computer and use it in GitHub Desktop.
Example of Flask admin making use of foreign keys and image upload. Just for illustrative proposes!
from flask import Flask, url_for
from flask_admin import Admin, form
from flask_sqlalchemy import SQLAlchemy
from flask_admin.contrib.sqla import ModelView
from jinja2 import Markup
"""
This just an illustrative example, take it as a concept example,
nothing more, it is not secure and does not handle image deletion.
Hereby more complete examples:
https://github.com/flask-admin/flask-admin/blob/master/examples/forms/app.py
https://gist.github.com/jrm2k6/8905880
"""
app = Flask(__name__, static_folder='static', static_url_path='/static')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = b'Your App Secret!!!'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), nullable=False, unique=True)
name = db.Column(db.String(255), nullable=False)
surname = db.Column(db.String(255), nullable=False)
email = db.Column(db.String(120), nullable=False, unique=True)
def __repr__(self):
return f'<User {self.username}>'
def __str__(self):
return self.username
class Image(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(55), nullable=False, unique=True)
path = db.Column(db.String(255))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
user = db.relationship('User', backref='user.thumbinail', lazy=True)
def __str__(self):
src = url_for('static', filename=self.path)
# Markup not working...!?!?!?!!
return Markup(f'<img src={src} height=12px> <strong>{self.title}</strong>')
class ImageView(ModelView):
def _list_thumbnail(view, context, model, name):
if not model.path:
return ''
return Markup('<img src="%s">' % url_for('static',
filename=form.thumbgen_filename(model.path)))
column_formatters = { 'path': _list_thumbnail }
# Alternative way to contribute field is to override it completely.
# In this case, Flask-Admin won't attempt to merge various parameters for the field.
form_extra_fields = {
'path': form.ImageUploadField('Image',
base_path=app.static_folder,
thumbnail_size=(100, 100, True))
}
class ImageView(ModelView):
def _list_thumbnail(view, context, model, name):
if not model.path:
return ''
return Markup('<img src="%s">' % url_for('static',
filename=form.thumbgen_filename(model.path)))
column_formatters = { 'path': _list_thumbnail }
# Alternative way to contribute field is to override it completely.
# In this case, Flask-Admin won't attempt to merge various parameters for the field.
form_extra_fields = {
'path': form.ImageUploadField('Image',
base_path=app.static_folder,
thumbnail_size=(100, 100, True))
}
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), nullable=False)
text = db.Column(db.Text)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'),
nullable=False)
author = db.relationship('User', backref=db.backref('posts'), lazy=True)
def __repr__(self):
return f'<Post: "ID":{self.id}, "TITLE":{self.title}>'
def __str__(self):
return self.title
db.init_app(app)
db.create_all()
# Add administrative views here
admin = Admin(app, name='microblog', template_mode='bootstrap3')
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Post, db.session))
admin.add_view(ImageView(Image, db.session))
if __name__=="__main__":
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment