如何使用flask在网站中添加额外字段字段.FieldLis

2024-09-30 06:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望用户能够添加或删除网站中的字段,我正在使用烧瓶和字段.字段列表你知道吗

我知道如何直接用javascript克隆DOM的field部分并重命名name,id等属性。。。有没有一个简单的方法可以用烧瓶/烧瓶的形式来做?我想达到图片中的效果(不一定要在那个布局中,我真的不在乎布局,因为我以后可以移动它) I want a new render of adding and removing fields 然后能把它传到后端,被烧瓶的形状识别出来。你知道吗

提前谢谢,我很感激=)

这是我的表格:

class AddressForm(FlaskForm):
addr = fields.StringField("address")

class MainForm(FlaskForm):
addressees = fields.FieldList(fields.FormField(AddressForm), min_entries=1, validators=[DataRequired()])

这是我的观点:

    def addressees_create():
        if request.method == 'POST':
            form = MainForm()
            if form.validate():
                print("is validate")
            else:
                print("was not validate")

            if form.validate_on_submit():
                print("the form was validated on submit")
            else:
                print("was not validated on submit")

            print(form.data)
            addressees = form.data["addressees"]
            for address in addressees:
                print("\t"+str(address))

            return render_template("my/template.html",form=form)
        else:
            form = MainForm()
            return render_template("my/template.html", form=form)

这是模板:

    <div>
        {% for item in form.addressees %}
            {{ item.hidden_tag() }}
            {{ item.addr }}
        {% endfor %}

        <div style="color: red;">
            {% for error in form.addressees.errors %}
                <span>{{ error }}</span>
            {% endfor %}
        </div>
    </div>

Tags: divformfieldsif烧瓶onaddresstemplate
1条回答
网友
1楼 · 发布于 2024-09-30 06:19:51

我也有这个问题。这是我的解决办法

class CreatePollForm(FlaskForm):
    title = StringField('Title', validators=[DataRequired()])
    options = FieldList(StringField())
    submit = SubmitField('Create')


<ul id="options">
    <li>
        <label for="options-0">Options-0</label>
        <input id="options-0" name="options-0" type="text" value="">
    </li>
    <li>
        <label for="options-1">
            Options-1
        </label>
        <input id="options-1" name="options-1" type="text" value="">
    </li>
    <li>
        <label for="options-2">Options-2</label>
        <input id="options-2" name="options-2" type="text" value="">
    </li>
    <li>
        <label for="options-3">Options-3</label>
        <input id="options-3" name="options-3" type="text" value="">
    </li>
    <li>
        <label for="options-4">Options-4</label>
        <input id="options-4" name="options-4" type="text" value="">
    </li>
</ul>

您可以这样引用这些数据:

form = CreatePollForm()
print(form.options.data)

相关问题 更多 >

    热门问题