问题
While writing custom validation for wtforms, is it possible to pass extra argument( like request)
For e.g
class MyForm(Form):
name = TextField('Name', [Required()])
def validate_name(form, field):
if len(field.data) > 50:
raise ValidationError('Name must be less than 50 characters')
I need to pass request object( or non form object), if possible to validate_name method. Is there any way for doing it?
回答1:
The easier way to proceed would be to pass the request
object to your form and store it as an attribute.
You could do this through the __init__
method , or by doing my_form.request = request
.
Then, you validate_name
method can access the request
at self.request
.
来源:https://stackoverflow.com/questions/14241330/wtforms-passing-extra-arguments-while-writting-custom-validation