Flask-提交按钮提交所有表单,而不是一个表单

时间:2018-10-27 20:19:36

标签: python html5 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('بستن تیکت')

2 个答案:

答案 0 :(得分:2)

呈现带有id属性的表单标签,对于Submit和input标签使用form属性。

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

与输入元素关联的表单元素(其表单所有者)。该属性的值必须是同一文档中元素的ID。如果不使用此属性,则该元素与其最近的祖先元素(如果有)相关联。此属性使您可以将元素放置在文档中的任何位置,而不仅仅是表单元素的后代。

更新,然后为submit views.py

使用不同的名称来命名if close_form.validate_on_submit() and close_form.close.data:
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)

edit-ticket.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") }}

答案 1 :(得分:0)

在表单上添加操作,而不是将其保留为空白:

<form method="post" action="/close-ticket"> ... </form>

<form method="post" action="/edit-ticket"> ... </form>

定义显式函数来处理每个动作。一个动作,一个功能-保持简单。拆分并重新使用每个登录逻辑。

@app.route('/close-ticket', methods=['POST'])
def close_ticket():
    if session['logged_in'] != True:
        return redirect(url_for('Login'))
    # closeForm handling, etc....

@app.route('/edit-ticket', methods=['POST'])
def edit_ticket():
    if session['logged_in'] != True:
        return redirect(url_for('Login'))
    # editForm handling, etc....