Search code examples
pythonflaskflask-admin

Access model's attrubutes inside of ModelView class


Sorry in advance if it's a stupid question, but I am still a bit confused. Reading the flask admin documentation hasn't given any result yet.

In this example flask admin image upload example there is a custom ModelView called ImageView:

class ImageView(sqla.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=file_path,
                                      thumbnail_size=(100, 100, True))
    }

In the _list_thumbnail(view, context, model, name) there is parameter model. Inside of this method I can access the attributes of the model.

My question is how can I access the model and its attributes outside of the _list_thumbnail(view, context, model, name) method but inside ImageView?

Thanks


Solution

  • Passing model data to fields defined in view could be painful. But luckily FileUploadField and its subclasses can get namegen function for generating names as an argument. It receives "dirty" model object as an argument:

    def name_generator(obj, file_data):
        return 'file_%d.png' % obj.id
    
    class ImageView(sqla.ModelView):
        form_extra_fields = {
            'path': form.ImageUploadField('Image',
                                          base_path=file_path,
                                          namegen=name_generator,
                                          thumbnail_size=(100, 100, True))
        }
    

    I also found out that generated filename may contain path to the file, not only the name of the file.

    Update: As @stamaimer found, this method doesn't work properly for objects which don't exist in database yet as they don't have IDs yet.