Flask-Admin automatically loads and inserts into the database

My user is modeled in SQLAlchemy as:

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    url_pic = Column(String(50), nullable=False)
    (...)

And I want to add the user to the database in Flask-Admin so that when I create the user, I can upload the photo directly, and the destination URL is parsed and passed for the url_pic field in the database.

I can already add users and upload photos (explain well in https://flask-admin.readthedocs.org/en/latest/quickstart/ ), but could not find any information on how to merge, add a user and upload a photo to that same point of view.

Any clue?

+4
source share
1

:

class User(Base):
   __tablename__ = 'users'
   id = Column(Integer, primary_key=True)
   url_pic = Column(String(50), nullable=False)
   pic = Column(LargeBinary, nullable=False)
   ...

ModelView flask.ext.admin.contrib.sqla. . .

from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.admin.form.upload import FileUploadField
from wtforms.validators import ValidationError
from flask.ext.admin import Admin
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask
import imghdr

app = Flask(__name__)
db = SQLAlchemy(app)

class UserAdminView(ModelView):

   def picture_validation(form, field):
      if field.data:
         filename = field.data.filename
         if filename[-4:] != '.jpg': 
            raise ValidationError('file must be .jpg')
         if imghdr.what(field.data) != 'jpeg':
            raise ValidationError('file must be a valid jpeg image.')
      field.data = field.data.stream.read()
      return True

   form_columns = ['id','url_pic', 'pic']
   column_labels = dict(id='ID', url_pic="Picture URL", pic='Picture')

   def pic_formatter(view, context, model, name):
       return 'NULL' if len(getattr(model, name)) == 0 else 'a picture'

   column_formatters =  dict(pic=pic_formatter)
   form_overrides = dict(pic= FileUploadField)
   form_args = dict(pic=dict(validators=[picture_validation]))

admin = Admin(app)
admin.add_view(UserAdminView(User, db.session, category='Database Administration'))
...

ModelView: , -!

+2

All Articles