如何覆盖Flask-Admin的edit_form(),将以前的值保留为占位符

时间:2015-03-06 18:48:34

标签: python-2.7 flask flask-admin

我正在尝试覆盖Flask-Admin的edit_form(),以便动态填充SelectField。我设法这样做了

class ProductForm(Form):
    order = IntegerField('order')
    name = TextField('name')
    category = SelectField('category', choices=[])
    image = ImageUploadField(label='Optional image',
                             base_path=app.config['UPLOAD_FOLDER_ABS'],
                             relative_path=app.config['UPLOAD_FOLDER_R'],
                             max_size=(200, 200, True),
                             endpoint='images',
                             )

class ProductsView(MyModelView):
    create_template = 'admin/create-products.html'
    edit_template = 'admin/edit-products.html'
    column_list = ('order', 'name', 'category', 'image')
    form = ProductForm
    column_default_sort = 'order'

    def edit_form(self, obj):
        form = self._edit_form_class(get_form_data(), obj=obj)
        cats = list(db.db.categories.find())
        cats.sort(key=lambda x: x['order'])
        sorted_cats = [(cat['name'], cat['name']) for cat in cats]
        form.category.choices = sorted_cats
        form.image.data = obj['image']
        return form

问题是现在/edit/视图中的表单默认nameorder字段为空,除非我将这两行添加到edit_form()

form.name.data = obj['name']
form.order.data = obj['order']

但是,如果我这样做,表单将忽略每一个更改(因为我已经设置了form.field_name.data?)

如何在正确覆盖edit_form()的同时将旧表单值保留为“占位符”?

1 个答案:

答案 0 :(得分:1)

我有类似的问题,感谢答案here我解决了它;

基本上你设置字段的默认值,然后调用单个字段process()方法,传入当前设置的值。

from wtforms.utils import unset_value

form.name.default = obj['name']
form.name.process(None, form.name.data or unset_value)
form.order.default = obj['order']
form.order.process(None, form.order.data or unset_value)