Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAdam Cameron
Python Web Development Techdegree Graduate 16,731 PointsWhy is 'password2' a string and not a reference to the field password2 itself? Can anyone explain this a bit more?
Intuition here says that 'password2'
, which Kenneth passes as the first argument of the validator EqualTo()
ought to refer to the value of that field itself instead of the string 'password2'
. What's the logic here?
2 Answers
Ryan S
27,276 PointsHi Adam,
I agree that passing in a string to refer to the other password seems a bit odd, especially when we are setting all this up in the form class itself and the fields are all defined right there.
But I think the reason for using a string begins with the fact that the form will eventually be rendered in html, and every input element (i.e., field) must have a "name" attribute.
As far as I understand, when a form is constructed in Flask, the field variable name that you have used to define a specific field in the form class will automatically become the "name" attribute of its corresponding input element. So when we refer to another field in EqualTo()
, we will be passing in the "name" of that input field, not the field variable itself, so a string will be required.
Hope this clears things up.
Nicolas Hampton
44,638 PointsAdam,
The best answer to this is looking at the source code for the "EqualTo" validator: https://github.com/wtforms/wtforms/blob/283b2803206825158834f1828bbf749c129b7c47/src/wtforms/validators.py#L88
Another student asked why the "form" reference that's passed into validators makes it possible to validate based on the value of other fields as well. The perfect example of this is a password and confirm password field, where the validity of one field is dependent on another.
Two things about this source code: the validator is a class, not a function. Don't let this throw you. The call method is basically the same as the function validators we're writing in this class. They're creating a class here to allow you to pass arguments to the init method to customize the validator method.
Inside EqualTo, the call method uses that string instead of a reference to password2, and here you can see why. Internally, EqualTo is using that string as a key for the form parameter!
Hope this helps!