Flask-Admin Custom Select2 Ajax Field
Asked Answered
W

1

10

I'm trying to extend a one-to-many field in my Flask-Admin app to use a custom Select2 Field. The javascript code for the field looks something like this:

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

I am unsure of what I need to change in my view code. I've tried something like this:

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)

but its not ajax and there is an error when trying to parse the list.

I feel I'm close, but need some guidance to get there, thanks for the help.

Womack answered 10/2, 2014 at 23:36 Comment(0)
D
-1

what you probably need is a 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
Displayed answered 16/8, 2014 at 9:31 Comment(1)
This isn't even syntactically correct. for x in lambda is trying to iterate over a function that's never evaluated.Fipple

© 2022 - 2024 — McMap. All rights reserved.