Flask-Admin Custom Select2 Ajax Field

I am trying to expand a one-to-many field in my Flask-Admin application 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'm not sure what I need to change in my code view. I 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 this is not ajax and an error occurs when trying to parse this list.

I feel like I'm around, but I need to be guided, thanks for the help.

+6
source share
1 answer

what you probably need 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 
-1
source

All Articles