Search code examples
pythonflaskflask-wtformsflask-admin

Using ImageUploadField in an InlineFormAdmin form


How to make a property in a model render as an image (upload) field in an inline form in Flask Admin ? I tried the code below - it is a slight variation of what can be found in the examples of flask-admin. I prefer to use ImageUploadField since it uses PIL to take care of generating thumbnails of images. The alternate approach is to use WTF directly which works well.

# Create models
# Location to LocationImage is one-to-many
class Location(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(64))

class LocationImage(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    alt = db.Column(db.Unicode(128))
    path = db.Column(db.String(64))

    location_id = db.Column(db.Integer, db.ForeignKey(Location.id))
    location = db.relation(Location, backref='images')

class InlineModelForm(InlineFormAdmin):
    form_label = 'Image'

    def __init__(self):
        return super(InlineModelForm, self).__init__(LocationImage)

    #This property doesn't seem to have any effect in an inline form
    form_extra_fields = {
        'path': ImageUploadField('Image', base_path=base_path)
    }

# Administrative class
class LocationAdmin(ModelView):
    inline_models = (InlineModelForm(),)

    def __init__(self):
        super(LocationAdmin, self).__init__(Location, db.session, name='Locations')

Solution

  • There was a bug with Flask-Admin. I raised an issue and submitted a PR which has been merged to master. Any release after v1.3.0 should have this fix.