Reputation: 127
I'm new to Flask. I've been looking at various tutorials and the only thing I've seen that looks like it should work doesn't.
I have a form class:
class CreateKardForm(FlaskForm):
kardTitle = StringField('Title')
contentText = TextAreaField('Content', [InputRequired(message="You must fill in some text.")])
keywords = StringField('Keywords', [InputRequired(message="Please enter at least one keyword. Separate keywords with commas.")])
createDate = DateField('Creation Date')
modifiedDate = DateField('Last Modified Date')
submit = SubmitField('Save')
And an html file:
<!DOCTYPE html>
<html lang="en">
{% extends "formbase.html" %}
{% block content %}
<div class="formwrapper>
<h1>Create a New IdxKard</h1>
<form action="" method="post" novalidate>
{{ form.hidden_tag() }}
...
<p>
{{ form.createDate.label }}<br>
{{ form.createDate }}
</p>
<p>
{{ form.modifiedDate.label }}<br>
{{ form.modifiedDate }}
</p>
<p>{{ form.submit() }}</p>
</form>
</html>
{% endblock %}
</html>
And a route:
@app.route('/createKard', methods=['GET', 'POST'])
def createKard():
print('In createKard')
creationDate = datetime.now()
print('creationDate=', creationDate)
form = forms.CreateKardForm()
if form.validate_on_submit():
print('In createKard in main')
title = request.form['kardTitle']
content = request.form['contentText']
keywords = request.form['keywords']
createDate = request.form['createDate']
modifiedDate = request.form['modifiedDate']
# do stuff
return render_template('createKard.html', createDate=creationDate, form=form)
I want that creationDate to show up in the form when it loads, but it doesn't. I suspect I am still fuzzy on exactly what is going on. I think because the user hasn't hit the submit button yet, that return with render_template should be displaying the HTML and passing in the createDate. When the user does hit the submit, the validate_on_submit is true and the rest of the code is run. Bottom line though, how do I pass a value into the form so it will be displayed?
Upvotes: 0
Views: 1029
Reputation: 2698
Before passing the instance of CreateKardForm
to render_template
, you have to set its createDate.data
:
@app.route('/createKard', methods=['GET', 'POST'])
def createKard():
print('In createKard')
creationDate = datetime.now()
print('creationDate=', creationDate)
form = forms.CreateKardForm()
form.createDate.data = creationDate # pre-populate the form
# ...
return render_template('createKard.html', createDate=creationDate, form=form)
Here is the result:
Upvotes: 1