I am writing a Flask app in which the user will have to enter all of the university courses they are planning to take for a semester. The data required is a code (e.g. 'CMPT') and a number (e.g. '101').
I want the user to be able to input up to 10 courses. I would like to do this by reusing the CourseForm I created, instead of manually creating the fields for each course. I have played around with FieldList and FormField to create a new form that uses the CourseForm, but I can't get it to display properly.
How can I create a form that has 10 slots for courses?
class CourseForm(Form):
code = SelectField('Course Code', choices=CHOICES)
number = IntegerField('Course Number')
@app.route(...)
def index():
form = CourseForm()
return render_template('main.html', title='Main', form=form)
main.html:
...
<form action="" method="post" name="course">
{{ form.hidden_tag() }}
<p>{{ form.code() }} {{ form.number() }}</p>
<p><input type="submit" value="Submit"></p>
</form>
...
You're on the right track with FieldList and FormField.
Start with your CourseForm.
class CourseForm(Form):
code = SelectField('Course Code', choices=CHOICES)
number = IntegerField('Course Number')
Then you'll need to encapsulate it inside another form. For the sake of this example I'll call it RegisteredCoursesForm. You can use max_entries to limit the number of entries to 10. If you always want 10 entries to be available, even if they won't all be filled in, you can also include min_entries.
class RegisteredCoursesForm(Form):
courses = FieldList(FormField(CourseForm), min_entries=10, max_entries=10)
# Any other fields can go here (e.g., user_id).
You'll want to pass this new form to your template instead of CourseForm.
def index():
form = RegisteredCoursesForm()
return render_template('main.html', title='Main', form=form)
Finally you can iterate over the courses field to get all of the fields contained without CourseForm.
<form action="" method="post" name="course">
{{ form.hidden_tag() }}
{% for course_form in form.courses %}
<p>{{ course_form.code }} {{ course_form.number }}</p>
{% endfor %}
<p><input type="submit" value="Submit"></p>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With