-
-
Notifications
You must be signed in to change notification settings - Fork 308
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add empty option in SelectField #348
Comments
my way is: # form.py
class TestForm(FlaskForm):
dropdownlist = SelectField('dropdownlist')
# view.py
@app.route('/your_route')
def your_function():
form = TestForm()
select_option = Model.query.with_entities('key', 'value').all()
form.dropdownlist.default = [('0', '-- select an option --')] + select_option
return ... of course you can add SelectField's option in Form init. |
Not exactly what I was hoping to... |
If you are using an ORM (sqlalchemy/django) then the wtforms E.g.: from wtforms.ext.sqlalchemy.fields import QuerySelectField
class AForm(Form):
category = QuerySelectField(
query_factory=lambda: Category.query,
allow_blank=True
) It hard to look past if you are already querying through ORM to get select options. Although the sqlalchemy extension is on the way out, to be replaced by WTForms-Alchemy in 3.0. |
This comment has been minimized.
This comment has been minimized.
My workaround for this was to include a custom validation function to not allow the first option, which might be something like "-- select an option --". I know this is not exactly what you were looking for and also 4 years late, but I hope this helps somebody haha # form.py
class MyForm(FlaskForm):
def validate_option(self, option_to_check):
if option_to_check == "-- select an option --":
raise ValidationError("Please select a role.")
option = SelectField(label="Choose an option", choices=[('-- select an option --'), ('Option 1'), ('Option 2'), ('Option 3'),
('Other')]) |
Note that the text shown should also be supported by translation to other languages. |
The best way for disable an option or 'validate' a select field its the following: the_field = SelectField(
'The Field',
choices=[('', 'Select any'), ('more_options', 'More Options')],
validators=[InputRequired()],
default=''
) Note: from wtforms import SelectField
from wtforms.validators import InputRequired |
Disabling the option with a HTML |
Hi there,
is there a way to add an empty option to a Selectfield ?
The only way I found is to add this to the choices before your actual choices:
But this requires validation on the backend since this option should be disabled by default.
How can I disable this option so that the rendered tag would be like:
The text was updated successfully, but these errors were encountered: