在ModelView类内部访问模型的属性 [英] Access model's attrubutes inside of ModelView class

查看:65
本文介绍了在ModelView类内部访问模型的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是一个愚蠢的问题,请先抱歉,但我仍然有些困惑.阅读flask的管理文档还没有任何结果.

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.

在此示例中,烧瓶管理映像上传例如,有一个名为ImageView的自定义ModelView:

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))
    }

_list_thumbnail(视图,上下文,模型,名称)中有参数模型.在此方法的内部,我可以访问模型的属性.

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

我的问题是如何在 _list_thumbnail(视图,上下文,模型,名称)方法之外但在ImageView内访问模型及其属性?

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?

谢谢

推荐答案

将模型数据传递到视图中定义的字段可能会很麻烦.但幸运的是, FileUploadField 及其子类可以使用 namegen 函数生成名称作为参数.它接收脏"模型对象作为参数:

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.

更新:正如@stamaimer所发现的,该方法不适用于数据库中尚不存在的对象,因为它们还没有ID.

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.

这篇关于在ModelView类内部访问模型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆