2

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?

1
  • I suggest that you change the class name. Example: Users Commented May 26, 2024 at 13:03

1 Answer 1

3
+50

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) 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot, I had search for a long time, this solution is very useful and simple!
Please explain "remove the choices=". How would forms.py look like?
Instead of SelectMultipleField('Select classes to assign this homework to', choices = [("1", "Class 1"), ("2","Class 2")]), use SelectMultipleField('Select classes to assign this homework to').

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.