Reputation: 1275
I am generating a field with WTForms using a code similar to this:
my_field = QuerySelectField(
'My Field',
query_factory=lambda: MyClass.query
)
But in this case I got back all my elements of type MyClass
and the first one is automatically selected.
If I change it in this way:
my_field = QuerySelectField(
'My Field',
query_factory=lambda: MyClass.query,
allow_blank = True
)
The default selection is now empty, which is what I want, but the empty selection is now valid, when instead I want it to be an error.
Is there a way to not have a default but still being able to not make the selection optional?
Upvotes: 1
Views: 971
Reputation: 3
You can create a custom validator to invalidate the default selection created by allow_blank = True
.
Using InputRequired()
or DataRequired()
would not work because the default "blank" selection has a value of __None
thus allowing the my_field
validation to pass.
from wtforms.validators import ValidationError
class Form(FlaskForm):
my_field = QuerySelectField(
'My Field',
query_factory=lambda: MyClass.query,
allow_blank = True
)
@staticmethod
def validate_my_field(self, field):
if field.data is None:
raise ValidationError("Please select a value.")
Upvotes: 0
Reputation: 9440
Adding a DataRequired
validation to the form for that field would seem the easiest way.
from wtforms import validators
my_field = QuerySelectField(
'My Field',
query_factory=lambda: MyClass.query,
allow_blank=True,
validators=[validators.DataRequired()]
)
Upvotes: 2