如何在不刷新页面的情况下在烧瓶中创建链式选择域?

Alv*_*eus 2 python jquery jinja2 flask flask-wtforms

我目前正在使用wtf处理地址表单,其中包含Country,State,City ..等等.数据库全部使用FK设置.

class Country(db.Model):
    __tablename__ = 'countries'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    users = db.relationship('User', backref='countries', lazy='dynamic')
class City(db.Model):
    __tablename__ = 'cities'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    countries_id = db.Column(db.Integer, db.ForeignKey('countries.id')) 
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试实现链式选择域排序效果以优化用户体验.期望的效果是在不离开或刷新页面的情况下根据先前的选择字段使选择字段拉取数据.

例如,用户在国家中选择澳大利亚,然后国家的第二个选择区域应仅包含澳大利亚的州.

我已经对这个主题做了一些研究,但是无法提出令人满意的解决方案.以下是我发现的两种可能尚未解决的解决方案.

1.使用jQuery-plugin,例如Chained.但是,这个插件需要逐行编码.如果我采用这种解决方案,那么至少会有另外400多条线路,这不是非常pythonic.例如:

<select id="series" name="series">
  <option value="">--</option>
  <option value="series-3" class="bmw">3 series</option>
  <option value="series-5" class="bmw">5 series</option>
  <option value="series-6" class="bmw">6 series</option>
  <option value="a3" class="audi">A3</option>
  <option value="a4" class="audi">A4</option>
  <option value="a5" class="audi">A5</option>
</select>
Run Code Online (Sandbox Code Playgroud)

2.使用Wtf的"选择具有动态选择值的字段",这也是不可取的,因为它只根据前一个选择字段的默认值拉取数据一次.例如:如果国家/地区的默认选择字段是澳大利亚,则州选择字段仅包含澳大利亚境内的州.当你改变国家选择字段说到美国时,州选择字段仍然只包含澳大利亚境内的州.下面是wtf文档中列出的此方法的教程:

class UserDetails(Form):
    group_id = SelectField(u'Group', coerce=int)

def edit_user(request, id):
    user = User.query.get(id)
    form = UserDetails(request.POST, obj=user)
    form.group_id.choices = [(g.id, g.name) for g in Group.query.order_by('name')]
Run Code Online (Sandbox Code Playgroud)

从上面的研究中,我认为满意的解决方案应该在两者之间,它肯定应该涉及一些Javascript来监视客户端活动而不向服务器发送请求.有没有人为烧瓶框架获得满意的解决方案?

dav*_*ism 9

如果你想在客户端上运行一些动态的东西,就无法编写一些JavaScript.幸运的是,这不是你估计的400多行.这个例子不使用WTForms,但这并不重要.关键部分是将可用选项作为JSON发送,并动态更改可用选项.这是一个单个文件可运行的Flask应用程序,它演示了基本的想法.

from flask import Flask, render_template_string

app = Flask(__name__)

@app.route('/')
def index():
    systems = {
        'PlayStation': ['Spyro', 'Crash', 'Ico'],
        'N64': ['Mario', 'Superman']
    }

    return render_template_string(template, systems=systems)

template = """
Run Code Online (Sandbox Code Playgroud)
<!doctype html>
<form>
    <select id="system">
        <option></option>
    </select>
    <select id="game"></select>
    <button type="submit">Play</button>
</form>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
    "use strict";

    var systems = {{ systems|tojson }};

    var form = $('form');
    var system = $('select#system');
    var game = $('select#game');

    for (var key in systems) {
        system.append($('<option/>', {'value': key, 'text': key}));
    }

    system.change(function(ev) {
        game.empty();
        game.append($('<option/>'));

        var games = systems[system.val()];

        for (var i in games) {
            game.append($('<option/>', {'value': games[i], 'text': games[i]}));
        }
    });

    form.submit(function(ev) {
        ev.preventDefault();
        alert("playing " + game.val() + " on " + system.val());
    });
</script>
Run Code Online (Sandbox Code Playgroud)
"""

app.run()
Run Code Online (Sandbox Code Playgroud)


Cle*_*leb 5

我最近遇到了类似的问题,并使用这个答案中的想法解决了它。

一个最小的例子可能如下所示:

在此处输入图片说明

因此,只有两个下拉列表,其中第二个取决于第一个的选定值;页面上的所有其他元素不受此选择的影响(这里我只使用一个复选框)。一旦做出选择,下拉菜单下方的按钮将触发一个动作,然后结果可以再次显示在页面上(这里,我只更新按钮下方的句子,当然你也可以做更合理的事情),例如到: 在此处输入图片说明

HTML 文件如下所示(位于templates/index.html):

<!DOCTYPE html>
<html lang="en">
  <head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <div class="container">
      <div class="header">
        <h3 class="text-center text-muted">Dynamic dropdowns</h3>
      </div>

      <div>
        Check me and I don't change status when you select something below
      </div><br>
      <div>
        <input class="form-check-input" type="checkbox" value="" id="use_me">Select me
      </div><br><br>

      <div class="row">
        <div class="form-group col-xs-6">
          <label for="all_classes">Select a class</label>
          <select class="form-control" id="all_classes">
            {% for o in all_classes %}
                    <option value="{{ o }}">{{ o }}</option>
            {% endfor %}
          </select>
        </div>
        <div class="form-group col-xs-6">
          <label for="all_entries">Select an entry</label>
          <select class="form-control" id="all_entries">
            {% for o in all_entries %}
                    <option value="{{ o }}">{{ o }}</option>
            {% endfor %}
          </select>
        </div>
      </div>

      <div>
        <button type="button" id="process_input">Process selection!</button>
      </div><br><br>
      <div id="processed_results">
        Here we display some output based on the selection
      </div>
    </div>
    <script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {

        $('#all_classes').change(function(){

          $.getJSON('/_update_dropdown', {
            selected_class: $('#all_classes').val()

          }).success(function(data) {
                $('#all_entries').html(data.html_string_selected);
           })
        });
        $('#process_input').bind('click', function() {

            $.getJSON('/_process_data', {
                selected_class: $('#all_classes').val(),
                selected_entry: $('#all_entries').val(),


            }).success(function(data) {
                $('#processed_results').text(data.random_text);
            })
          return false;

        });
      });
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

对应的python脚本如下所示:

from flask import Flask, render_template, request, jsonify
import json

# Initialize the Flask application
app = Flask(__name__)


def get_dropdown_values():

    """
    dummy function, replace with e.g. database call. If data not change, this function is not needed but dictionary
    could be defined globally
    """

    class_entry_relations = {'class1': ['val1', 'val2'],
                             'class2': ['foo', 'bar', 'xyz']}

    return class_entry_relations


@app.route('/_update_dropdown')
def update_dropdown():

    # the value of the first dropdown (selected by the user)
    selected_class = request.args.get('selected_class', type=str)

    # get values for the second dropdown
    updated_values = get_dropdown_values()[selected_class]

    # create the value sin the dropdown as a html string
    html_string_selected = ''
    for entry in updated_values:
        html_string_selected += '<option value="{}">{}</option>'.format(entry, entry)

    return jsonify(html_string_selected=html_string_selected)


@app.route('/_process_data')
def process_data():
    selected_class = request.args.get('selected_class', type=str)
    selected_entry = request.args.get('selected_entry', type=str)

    # process the two selected values here and return the response; here we just create a dummy string

    return jsonify(random_text="you selected {} and {}".format(selected_class, selected_entry))


@app.route('/')
def index():

    """
    Initialize the dropdown menues
    """

    class_entry_relations = get_dropdown_values()

    default_classes = sorted(class_entry_relations.keys())
    default_values = class_entry_relations[default_classes[0]]

    return render_template('index.html',
                           all_classes=default_classes,
                           all_entries=default_values)


if __name__ == '__main__':

    app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)

  • @Picarus:我刚刚复制并粘贴了上面的代码,它对我来说效果很好。我使用python 3.6.5和flask 1.0.2。您在控制台中得到什么样的输出?当我加载页面时,我得到: `127.0.0.1 - - [17/Jan/2019 08:40:37] "GET / HTTP/1.1" 200 -` 然后一旦我选择了某些内容:`127.0.0.1 - - [ 2019 年 1 月 17 日 08:40:46]“GET /_update_dropdown?selected_class=class1 HTTP/1.1”200 -`。当你改变“class”时你会看到什么? (2认同)