Sunday, 12 January 2020

Passing a variable into a WTForms class

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">
        
        
</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?



from Passing a variable into a WTForms class

No comments:

Post a Comment