Reputation: 70
I'm relatively inexperienced with Python and Flask, and am stuck trying to pass a variable to a WTForms class.
Here's what I have:
views.py
@app.route('/teacher/tasks/new')
@login_required
def new_hw_task():
classes = Class.query.filter_by(userid=current_user.userid).all()
form = NewTaskForm(classes = classes)
return render_template('/teacher/new_hw_task.html', form=form)
forms.py
class NewTaskForm(FlaskForm):
classes = SelectMultipleField('Select classes to assign this homework to', choices = [("1", "Class 1"), ("2","Class 2")])
new_hw_task.html
<div class="form-group">
{{ form.classes.label }}
{{ form.classes(class_="form-control selectpicker", placeholder=form.classes.description, title="Select at least one class to assign", show_tick=true)}}
</div>
I want the classes
variable (an instance of a Class
class defined in models.py - yes, yes, I know how sloppy it is to have a class called 'Class') to be accessible in forms.py so that I can replace the choices in the SelectMultipleField
with ones from classes
. However, I can't find a way to pass it through (you can see that I've tried putting classes=classes
into the parentheses after NewTaskForm).
Actually, my preferred way to do this would be to simply access current_user
(the session-based object set by flask_login) from within forms.py, but I appear to be unable to do that either, even if I import current_user at the top of the file.
Is anybody able to explain to me where I'm going wrong here, please?
Upvotes: 2
Views: 3509
Reputation: 686
The WTForms documentation for SelectField
explains how to pass variables into a form from a view. It's as simple as assigning a list of choices to form.field.choices
. In turn, you remove the choices=
keyword argument from the field constructor.
Adapted for your case, it would look like this.
@app.route('/teacher/tasks/new')
@login_required
def new_hw_task():
classes = Class.query.filter_by(userid=current_user.userid).all()
form = NewTaskForm()
form.classes.choices = classes
return render_template('/teacher/new_hw_task.html', form=form)
Upvotes: 3