简体   繁体   English

使用带有flask-wtforms的Select2

[英]Using Select2 with flask-wtforms

After select2 manipulates the dropdown field the regular use of form.owner_id.data yields None . 在select2操作下拉字段后,经常使用form.owner_id.data产生None How can I extract the selected option from a select2 field. 如何从select2字段中提取所选选项。

If I disable the select2 javascript, wtforms will work just fine and I will be able to use form.owner_id.data . 如果我禁用select2 javascript,wtforms将正常工作,我将能够使用form.owner_id.data (but it looks ugly) (但看起来很难看)

screenshot of rendered form 渲染形式的屏幕截图

forms.py forms.py

class ProjectForm(FlaskForm):
    owner_id = SelectField('Owner:', [validators.Required()], choices=[], render_kw={"placeholder": "Owner company *"})

(rest of form has been truncated for simplicity) (为简单起见,其余形式已被截断)

views.py views.py

@app.route('/new_project/<int:company_id>', methods=('GET', 'POST'))
def new_project(company_id):
    membership = Membership.query.filter_by(user_id=current_user.id, company_id=company_id).first()
    company = Company.query.filter_by(id=company_id).first_or_404() 
    form = ProjectForm()

    form.owner_id.choices = [(str(comp.id), repr(comp)) for comp in Company.query.all()]

    form.client_id.choices = [(str(comp.id), repr(comp)) for comp in Company.query.all()]

    form.contractor_id.choices = [(str(comp.id), repr(comp)) for comp in Company.query.all()]

    form.membership_id.choices = [(str(comp.id), repr(comp)) for comp in Company.query.all()]

    if request.method == 'POST':
        flash(str(form.owner_id.data), 'success')

    if form.validate_on_submit():
        project = Project()
        connection = Assignment()

        # PROJECT DETAILS
        project.title = form.title.data
        project.description = form.description.data
        project.owner_id = int(form.owner_id.data)

_macro _macro

{% macro render_select_field(field, placeholder='Select...', label='Select an option below') %}
<div class="form-group">
    <label>{{ label }}</label>
    <select data-placeholder="{{ placeholder }}" class="select-size-xs">
        <option></option>
          {% for choice in field.choices %}
              <option value="{{ choice[0] }}">{{ choice[1] }}</option>
            {% endfor %}
    </select>
    {% if field.errors %}
    {% for error in field.errors %}
      <span class="help-block text-danger"><i class="icon-cancel-circle2 position-left"></i>{{ error }}</span>
    {% endfor %}
  {% endif %}
</div>
{% endmacro %}

html HTML

<form method="POST" action="{{ url_for('new_project', company_id=company.id) }}" enctype="multipart/form-data" role="form">
            <div class="panel panel-body login-form">
                <div class="text-center">
                    <div class="icon-object text-muted"><i class="icon-plus2"></i></div>
                </div>

                {{ form.hidden_tag() }}
                <div class="text-center form-group"><span>Project details</span></div>
                {{ new_render_field(form.title, icon="icon-quill2", class_='form-control') }}

                {{ new_render_field(form.description, icon="icon-stack-text", class_='form-control', rows=10) }}

                {{ render_select_field(form.owner_id, placeholder="Who's doing the work?", label="Select the owner company") }}

                {{ render_select_field(form.client_id, placeholder="Where do the bills go?", label="Select the client company") }}

                {{ new_render_field(form.default_client_rate, icon="icon-price-tag", class_='form-control') }}

                {{ new_render_field(form.default_contractor_rate, icon="icon-price-tag", class_='form-control') }}


                <!-- THE REST OF FORM HAS BEEN TRUNCATED FOR SIMPLICITY -->
                <div class="form-group">
                  <button type="submit" class="btn bg-pink-400 btn-block">Create</button>
                </div>
            </div>
        </form>

So after analyzing the select field in the inspect window, it became apparent that the select field is missing the name="{{ field.name }}" that wtforms requires in order to validate the form. 因此,在检查窗口中的select字段进行分析后,很明显select字段缺少wtforms所需的name="{{ field.name }}"以验证表单。 The simple change made in my _macro was from this: 我的_macro中的简单更改来自于:

<select data-placeholder="{{ placeholder }}" class="select-size-xs">

To this: 对此:

<select data-placeholder="{{ placeholder }}" class="select-size-xs" name="{{ field.name }}">

With this addition wtforms can now validate, and find the selected option returning the proper id for form.owner_id.data . 通过此添加,wtforms现在可以验证,并找到所选选项,返回form.owner_id.data的正确id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM