python - Flask - 提交按钮提交所有表单而不是一张表单

标签 python html flask flask-wtforms wtforms

我在其中一个页面中使用两种表单,一种用于关闭票证,另一种用于发送回复。 但问题是,当我提交其中一份时,另一份也提交了!并显示闪光按摩。所以我有两次闪光按摩! 这变得更加复杂,因为我正在检查一些条件以显示第一种形式,在这种情况下,该形式甚至不再出现,我有两次闪光按摩!

@app.route('/edit-ticket', methods=['GET', 'POST'])
def edit_ticket():
if session['logged_in'] == True:
    trackingNumberLink = int(request.args.get('trackingNumber'))
    closeForm = CloseTicket()
    editForm = EditTicket()
    GetTicketStatus = tickets.find_one({"trackingNumber": trackingNumberLink})
    if closeForm.validate_on_submit():
        tickets.update_one({"trackingNumber": trackingNumberLink},
                           {"$set": {"status": "پاسخ داده شده", "order": 2}})
        flash(u"تیکت مورد نظر با موفقیت بسته شد.")
    if editForm.validate_on_submit():
        replyDate = jdatetime.datetime.now()
        tickets.update_one({"trackingNumber": trackingNumberLink},
                           {"$set": {"status": "در حال بررسی", "order": 1}})
        tickets.update_one({"trackingNumber": trackingNumberLink},
                           {"$push": {"replies": {"rep": {"mass": editForm.ticketMassage.data,
                                                          "date": replyDate.strftime("%H:%M:%S %d-%m-%y "),
                                                          "HowSent": "user"}}}})
        flash(u"پاسخ با موفقیت ارسال شد.")
    return render_template('edit-ticket.html', Title="ویرایش تیکت", closeForm=closeForm,
                           editForm=editForm, CanUserCloseTicket=GetTicketStatus)
else:
    return redirect(url_for('Login'))

HTML:

{% extends "layout.html" %}
{% block content_main %}
<div class="container content-box">
    <div class="row">
        <div class="col-sm-12">
            <div class="FormSection center-form">
                <fieldset class="form-group">
                    <legend class="border-bottom mb-4">ویرایش تیکت</legend>
                </fieldset>
                <form method="post" action="">
                    {{ editForm.hidden_tag() }}
                    <div class="form-group">
                        {{ editForm.ticketMassage.label(class="form-control-label") }}
                        {% if editForm.ticketMassage.errors %}
                            {{ editForm.ticketMassage(class="form-control-lg is-invalid") }}
                            <div class="invalid-feedback">
                                {% for error in editForm.ticketMassage.errors %}
                                    <span>{{ error }}</span>
                                {% endfor %}
                            </div>
                        {% else %}
                            {{ editForm.ticketMassage(class="form-control-lg") }}
                        {% endif %}
                    </div>
                    <div class="form-group">
                        {{ editForm.submit(class="btn btn-outline-info") }}
                    </div>
                </form>
            </div>
            {% if CanUserCloseTicket['status'] != "پاسخ داده شده" %}
                <div class="FormSection center-form">
                    <form method="post" action="">
                        {{ closeForm.hidden_tag() }}
                        <div class="form-group">
                            {{ closeForm.submitCloseTicket(class="btn btn-outline-info") }}
                        </div>
                    </form>
                </div>
            {% endif %}
        </div>
    </div>
</div>
</div>
{% endblock content_main %}

表单类:

class EditTicket(FlaskForm):
    ticketMassage = TextAreaField('متن پیام:',
                              description=u'پاسخ خود را بنویسید.',
                              validators=[data_required(), Length(min=20, max=500)], )
    submit = SubmitField('ویرایش تیکت')


class CloseTicket(FlaskForm):
    submitCloseTicket = SubmitField('بستن تیکت')

最佳答案

使用 id 属性呈现表单标签,并使用 form 属性为提交和输入标签呈现。

<form id="edit-ticket">
    {{ form.submit(form="edit-ticket") }}

The form element that the input element is associated with (its form owner). The value of the attribute must be an id of a element in the same document. If this attribute isn't used, the element is associated with its nearest ancestor element, if any. This attribute lets you to place elements anywhere within a document, not just as descendants of form elements.

更新submit使用不同的名称,然后在views.pyif close_form.validate_on_submit()和close_form.close中使用不同的名称。数据:

from flask import Flask, render_template
from flask_wtf import FlaskForm, CSRFProtect
from wtforms.fields import SubmitField, TextAreaField

app = Flask(__name__)


app.config['SECRET_KEY'] = '^%huYtFd90;90jjj'
app.config['UPLOADED_FILES'] = 'static/files'


csrf = CSRFProtect(app)


class EditTicketForm(FlaskForm):
    ticket_message = TextAreaField()
    edit = SubmitField()


class CloseTicketForm(FlaskForm):
    message = TextAreaField()
    close = SubmitField()


@app.route('/edit-ticket', methods=['GET', 'POST'])
def edit_ticket():
    close_form = CloseTicketForm()
    edit_form = EditTicketForm()
    if close_form.is_submitted() and close_form.close.data:
        if close_form.validate():
            x = close_form.message.data
            return x.upper()
    if edit_form.is_submitted() and edit_form.edit.data:
        if edit_form.validate():
            y = edit_form.ticket_message.data
            return y.upper()
    return render_template('edit-ticket.html', close_form=close_form, edit_form=edit_form)


if __name__ == "__main__":
    app.run(debug=True)

编辑票证.html

<form method="post" id="edit-form" novalidate></form>
<form method="post" id="close-form" novalidate></form>
    {{ edit_form.csrf_token(form="edit-form") }}
    {{ close_form.csrf_token(form="close-form") }}
    {{ edit_form.ticket_message(form="edit-form") }}
    {{ edit_form.edit(form="edit-form") }}
    {{ close_form.message(form="close-form") }}
    {{ close_form.close(form="close-form") }}

关于python - Flask - 提交按钮提交所有表单而不是一张表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53025939/

相关文章:

html - 仅使用 CSS 的砌体式布局

python - flask : TypeError: 'str' object is not callable

python - pyparsing:忽略任何不匹配的标记

python - tensorflow 自动编码器的输出始终相同

html - 在保持 parent 填充的同时使 child 可滚动

python - flask蓝图文件结构

python - 如何从 Flask 中的 HTTP 删除访问正文?

Python设计——初始化、设置和获取类属性

python - 如何使用 pandas 用名称替换变量

html - @import 媒体查询 css 问题