flask/flask-admin中的Select2字段实现 [英] Select2 field implementation in flask/flask-admin

查看:406
本文介绍了flask/flask-admin中的Select2字段实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的烧瓶视图之一中实现Select2字段.基本上,我要在Flask应用程序视图(而不是flask admin模型视图)中使用与Flask-admin模型创建视图相同的select2字段.目前,我的解决方案是使用看起来像这样的wtforms QuerySelectField

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())

这使我可以加载和选择所需的所有数据,但是它不提供select2搜索框等.目前,我从flask/admin/form/fields和flask中找到的都是Select2FieldSelect2Widget /admin/form/widgets类似于本文 https://stackoverflow .com/questions/24644960/how-to-steal-flask-admin-tag-form-field 以及 http://ivaynberg.github.io/select2/ 据我了解,这些可以重用,这意味着不需要其他自定义小部件,自定义字段.

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.

如果有人可以提供有关flask应用程序中select2字段实现的更多信息(包括视图,模板,表单文件以及如何正确连接"必要的js和css文件,以及如何使用我需要的数据库模型).

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).

推荐答案

这对我有用:

...
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())

在您的模板中:

{% 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.

这篇关于flask/flask-admin中的Select2字段实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆