Flask-Admin自定义Select2 Ajax字段

时间:2014-02-10 23:36:39

标签: javascript python ajax flask flask-admin

我尝试在Flask-Admin应用中扩展一对多字段以使用自定义Select2字段。该字段的javascript代码如下所示:

function format(data) {
    if (!data.id) return data.text; // optgroup
    return "<img class='flag' src='" + data.text + "'/>" + data.id;
}    
function formatSelection(data) {
    return data.id;
}
$("#da2").select2({
    maximumSelectionSize: 3,
    formatResult: format,
    formatSelection: formatSelection,
    escapeMarkup: function(m) { return m; }
});

我不确定在视图代码中需要更改的内容。我尝试过这样的事情:

class PostForm(wtf.Form):
    title = fields.TextField('Title')
    photos = fields.SelectField('Photo', widget=widgets.Select(multiple=True), id='da2')

class PostView(ModelView):
    form = PostForm

def _feed_user_choices(self, mform):
        photos = Photo.query.all()
        mform.photos.choices = [(x.path, url_for('static',
                                                 filename=form.thumbgen_filename(x.path))) for x in photos]
        return mform

def create_form(self):
    form = super(Post2View, self).create_form()
    return self._feed_user_choices(form)

但它不是ajax,并且在尝试解析列表时出错。

我觉得我很接近,但需要一些指导才能到达那里,感谢您的帮助。

1 个答案:

答案 0 :(得分:-1)

你可能需要的是一个lambda

def _feed_user_choices(self, mform):
    mform.photos.choices = [(x.path, url_for('static',filename=form.thumbgen_filename(x.path))) for x in lambda: Photo.query.all()]
    return mform