提交后如何将字段值保存在表单中?

2024-05-06 20:31:24 发布

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

提交表单后,字段值似乎设置为空。我正在执行一些表单验证;如果表单无效,我会让它显示错误列表中的错误消息,但我希望字段值保持不变。有办法吗?

这是验证表单的我的视图:

@app.route('/booking', methods=['GET', 'POST'])
def booking():
    errors = [] 
    if request.method == 'GET':     
        return render_template('booking.html', errors=errors)
    else:
        # grab values from form fields and store them in objects
        start_date = request.form['start_date']
        end_date = request.form['end_date']
        name = request.form['name'].strip()
        email = request.form['email'].strip()       

        # check if all fields are non-empty and raise an error if not
        if not start_date or not end_date or not name or not email:
            errors.append('Please enter all the fields.')
        else:
            # converts dates to Unix time-stamp for easier validation/calculations
            start_timestamp = dt.strptime(start_date, "%d/%m/%Y")
            end_timestamp = dt.strptime(end_date, "%d/%m/%Y")

            # checks to see if dates are valid          
            if start_timestamp > end_timestamp or end_timestamp < start_timestamp:              
                errors.append('Please enter a valid date range')
            else:
                #checks to see if booking has already been taken
                bookings = read_file('app/static/bookings.csv')     
                for i in bookings:
                    s_date = dt.strptime(i[0], "%d/%m/%Y")
                    e_date = dt.strptime(i[1], "%d/%m/%Y")
                    if s_date <= start_timestamp <= e_date:
                        errors.append('Booking has already been taken, please select another date')
                        break

            # checks to see if email address is valid using regex
            if not valid_email_address(email):
                errors.append('Please enter a valid email address')         

            #if no errors have occured then write booking to file
            if not errors:
                new_booking = [start_date, end_date, name, email]
                bookings.append(new_booking)
                write_file(bookings, 'app/static/bookings.csv')
                return render_template('booking.html')
    return render_template('booking.html', errors=errors)

这是表单的模板:

<div id="main-wrapper">
    <div id="main">     
        <div id="info">
            {% if errors %}
            {% for error in errors %}
            <div><p>{{ error }}</p></div>
            {% endfor %}
            {% endif %}
            <form action = "booking" method="post">
            <input id="start_date" type="text" name="start_date">
            <input id="end_date" type="text" name="end_date">
            <input type="text" name="name" />
            <input type="text" name="email" />

            <input type="submit" value="Submit">
        </div>
    </div>
</div>

Tags: namedivform表单dateifemailrequest
1条回答
网友
1楼 · 发布于 2024-05-06 20:31:24

最好使用一个表单库,比如WTForms(以及相关的扩展名Flask-WTF),而不是手动完成这一切。

但如果你用这种方法,那就相当有远见了。您需要提供从request.form到HTML输入的值。

<input id="start_data" type="text" name="start_date" value="{{ request.form['start_date'] }}"/>

相关问题 更多 >