Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the right way to optionally require a field using Flask-WTForms?

I'm using Flask with Flask-WTForms and am writing an admin page where it's possible to update values for a user - including the password.

I'm using the same form page that I use for registration, but since it's not requisite that the password be updated, I don't want to require it. What is the right way to do this with Flask-WTForms?

I've got my UserForm in forms.py and I was thinking of making a custom validator and have a file-level require_password option that would override the default check. I'm fairly new to WTForms, and somewhat new to Flask.

like image 933
Wayne Werner Avatar asked Oct 06 '22 09:10

Wayne Werner


1 Answers

This solution seems to do what I want:

In forms.py,

from flask.ext.wtf import Optional

def make_optional(field):
    field.validators.insert(0, Optional())

#Rest of code here...

Then inside my flask endpoint I can call:

user_form = UserForm()
forms.make_optional(user_form.password)
if user_form.validate_on_submit():
    #Go on your merry way!

That seems to do what I wanted - keep all the other validation (e.g. confirmation), while ignoring anything if there is no password present.

like image 175
Wayne Werner Avatar answered Oct 10 '22 01:10

Wayne Werner