Access model's attrubutes inside of ModelView class

坚强是说给别人听的谎言 提交于 2019-12-06 11:42:31

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.

As I commented in the first answer, You can't access the id of the current instance of the model. In spite of the instance is created, it haven't be commited to the database. There is no primary key of the current instance. But the other field is existence, maybe you can use other field instead of the primary key.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!