Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 field implementation in flask/flask-admin

I'm trying to implement Select2 field in one of my flask views. Basically I want the same select2 field in my flask application view (not a flask admin modelview) as in Flask-admin model create views. Currently my solution has been QuerySelectField from wtforms that looks something like this

class TestForm(Form):
    name= QuerySelectField(query_factory=lambda: models.User.query.all())

This allows me to load and select all the data I need, but it does not provide select2 search box etc. Currently all that I have found is Select2Field and Select2Widget from flask/admin/form/fields and flask/admin/form/widgets similarly like in this post https://stackoverflow.com/questions/24644960/how-to-steal-flask-admin-tag-form-field and also select2 documentation at http://ivaynberg.github.io/select2/ As I understand these could be reusable, meaning there is no need for other custom widgets, custom fields.

Would be grateful if someone could provide more information about select2 field implementation in flask application (including views, templates, forms files and how to correctly "connect" with neccessary js and css files, also how to load the field up with the database model I need).

like image 709
fbeastz Avatar asked Oct 31 '14 22:10

fbeastz


1 Answers

This worked for me:

...
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from flask_admin.form.widgets import Select2Widget
...

class TestForm(Form):
    name= QuerySelectField(query_factory=lambda: models.User.query.all(),
                           widget=Select2Widget())

And in your template:

{% extends "admin/master.html" %}
{% import 'admin/lib.html' as lib with context %}

{% block head %}
    {{ super() }}
    {{ lib.form_css() }}
{% endblock %}

{% block body %}
...
{% endblock %}

{% block tail %}
    {{ super() }}
    {{ lib.form_js() }}
{% endblock %}

I can try to put together a minimal working example if necessary.

like image 187
PiQuer Avatar answered Nov 08 '22 23:11

PiQuer