我正在寻找一种简单的方法,用文本文件中的数据预先填充表单的字段。
以下是我的导入:
#For Flask
from flask import Flask, render_template, flash, request, redirect, url_for, send_file
#For Web Form
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField, SelectField, RadioField, IntegerField, DateTimeField, DecimalField, FloatField
from werkzeug.utils import secure_filename
import re #For Regex
我的表格有以下课程:
class MainForm(Form):
#Regex
reEmail_comp = re.compile('^.+@.+\..+$')
reJobname_comp = re.compile('[^\s]+[\w]+$')
#Form Fields
familyname = TextField('Family Name:',
validators=[validators.DataRequired()])
firstname = TextField('First Name:',
validators=[validators.DataRequired()])
email = TextField('Email:',
validators=[validators.DataRequired(),
validators.Length(min=3, max=51),
validators.Regexp(regex=reEmail_comp)])
# Copy List of Job Templates
list_job_name = list_job_templates
# Create List of Tuples
choices_list = list(zip(list_job_name,list_job_templates))
# Generate string to be evaluate as analyses Radiofield
radio_string = ("RadioField('Analysis Type:',"
"validators=[validators.DataRequired()],choices="+str(choices_list)+")")
# Attribute value to element as a variable
locals()["analyses"] = eval(radio_string)
jobname = TextField('Job Name:',
validators=[validators.DataRequired(),
validators.Length(min=3, max=100),
validators.Regexp(regex=reJobname_comp)])
jobdescription = TextAreaField('Job Description:',
validators=[validators.Optional(),
validators.Length(min=0, max=10000)])
以下观点:
@app.route('/home', methods=['GET', 'POST'])
def home():
form = MainForm(request.form)
print(form.errors)
if request.method == 'POST':
familyname=request.form['familyname']
firstname=request.form['firstname']
email=request.form['email']
analyses=request.form['analyses']
jobname=request.form['jobname']
jobdescription=request.form['jobdescription']
if jobdescription == "":
jobdescription = "No Description"
nextpage=request.form['submit'] #Get submission button value
if form.validate():
#Print Temp file
print("||".join(["Family Name={}".format(familyname),
"First Name={}".format(firstname),"E-Mail={}".format(email),
"Analyse={}".format(analyses),"Job Name={}".format(jobname),
"Job Description={}".format(jobdescription)]),
file=open(submission_dir+"temp1", "w"))
#Redirections following which button has been clicked
if nextpage == 'Continue to Submission':
return redirect(url_for('nextpage'))
else:
return redirect(url_for('nextbis'))
else:
flash('Error: Please make sure that all the fields are correctly filled.')
return render_template('home.html', form=form)
用户可以访问表单并填写表单。 正如您在视图中看到的那样,在用户提交其信息后,所有信息都存储在临时“temp1.txt”文件中。 我想做的是让用户选择回到这个表格,以防他想修改他之前提交的信息。
为了简化这一点,我希望表单显示相同的字段,但这次预先填充了上一次提交的临时文本文件中的信息。
我怎么能以简单的方式做到这一点?
答案 0 :(得分:2)
如果您创建了一个表单并从请求中填充了该表单,则可以使用文件值完成相同的操作。
form = MainForm(read_file_in_correct_format())
其中read_file_in_correct_format
方法返回对象{fieldname:value}。保存为JSON可能更好,因此您可以轻松地解析它并支持更复杂的结构。
您所要做的就是根据request.method
@app.route('/home', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
# so if form is submitted, populate it from request
form = MainForm(request.form)
...
else:
# if we are just viewing form, then try to load stored values from temp1.txt
form = MainForm(read_file_in_correct_format())