提交后如何将字段值保留在表单中? [英] How can I keep field values in a form after submit?

查看:79
本文介绍了提交后如何将字段值保留在表单中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提交表单后,似乎字段值未设置为空.我正在做一些表格验证;如果表单无效,我将显示错误列表中的错误消息,但我希望保留字段值.有办法吗?

After submitting a form it appears that the field values are set back to nothing. I am doing some form validation; if the form is invalid I am having it display an error message from a list of errors but I wish for the field values to stay. Is there a way to do this?

这是我验证表单的视图:

This is my view that validates the form:

@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>

推荐答案

最好使用诸如 WTForms (以及相关的扩展名 Flask-WTF ),而不是手动完成所有操作.

You'd be better off using a form library such as WTForms (and the associated extension Flask-WTF) instead of doing this all manually.

但是,如果您设置了此方法,那么它很简单.您需要将request.form的值提供给HTML输入.

But if you're set on this method, then it's pretty traightforward. You need to provide the value from request.form to the HTML inputs.

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

这篇关于提交后如何将字段值保留在表单中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆