Search code examples
pythonflaskflask-admin

Flask-Admin | How to fix route to the image


I have a question according to image path in Flask. I have a DB model Image, that contains all necessary info about image, including path - '/animals/sometype/image.jpg'.

I'm using Flask-admin module, and the problem is the wrong path to the image in editing mode. Here's a code:

class ImageView(ModelView):
    edit_template = 'image_edit.html'

    def _list_thumbnail(view, context, model, name):
        if not model.path:
            return ''
        return Markup('<img src="%s">' % url_for('static', filename=('images' + model.path)))

column_formatters = {
    'path': _list_thumbnail
}

form_extra_fields = {
    'path': form.ImageUploadField('Image', base_path='static/images', url_relative_path='images/')
}

For column formatters path is correct, but for the extra fields is wrong, resulting in 404 error: http://127.0.0.1:5000/static//animals/birds/the_bird-wallpaper-1366x768.jpg

How can I solve this? Also, I was thinking about passing an image to the custom edit template, but I don't understand, how to do it in Flask-Admin.


Solution

  • I've found a solution to pass an image to the edit view in Flask-admin without ImageUploadField. The solution is simple, all I need is to pass an image id from DB and use it in Jinja template.

    class ImageView(ModelView):
    edit_template = 'image_edit.html'
    
    @expose('/edit/', methods=['GET', 'POST'])
    def edit_view(self):
        id = request.args.get('id')
        self._template_args['image'] = db.session.query(Image.path).filter(Image.id == id).first()[0]
        return super(ImageView, self).edit_view()
    

    And HTML template:

    {% extends "admin/model/edit.html" %}
    {% block body %}
      <img src=/static/images/{{ image }}/>
      {{ super() }}
    {% endblock %}