You can create your own TagField
and add it to your ModelView.
You will have to override some field functions.
I have put together a demo application that uses select2 version 4 and is a bit more detailed than this answer.
The tag field:
class CustomTagField(Select2TagsField):
widget = CustomTagWidget(multiple=True)
def pre_validate(self, form):
pass
def process_formdata(self, valuelist):
if valuelist:
self.data = []
for tagname in valuelist:
rv = Tag.query.filter_by(name=tagname).first()
if rv:
self.data.append(rv)
else:
self.data.append(Tag(name=tagname))
else:
self.data = []
def iter_choices(self):
self.blank_text = ""
tags = list(set([str(tag.name) for tag in Tag.query.all()]))
model_tags = [tag.name for tag in self.object_data]
self.choices = [[tag, tag] for tag in tags]
# Yield empty object in order to have an empty placeholder
yield (u'__None', self.blank_text, self.data is None)
for value, label in self.choices:
yield (value, label, value in model_tags)
Custom widget: (similar to Select2TagsWidget
, but does not set data-role
so form.js
will not make it a regular select2 field)
class CustomTagWidget(widgets.Select):
def __call__(self, field, **kwargs):
kwargs.setdefault('data-tags', '1')
# Or call select2 in tags mode
allow_blank = getattr(field, 'allow_blank', False)
if allow_blank and not self.multiple:
kwargs['data-allow-blank'] = u'1'
return super(CustomTagWidget, self).__call__(field, **kwargs)
In your admin:
form_extra_fields = {
'tags': CustomTagField(
'Tags',
),
}
Then override your admin template to call select2 in tag mode on your field(admin/js/form.js
will try to style the field as well):
$('#tags').select2({
tags: true,
});