Kilrathy
Kilrathy

Reputation: 275

WTForms RadioField default values

I'm generating a html form with wtforms like this:

<div class="control-group">
    {% for subfield in form.time_offset %}
    <label class="radio">
        {{ subfield }}
        {{ subfield.label }}
    </label>
    {% endfor %}
</div>

My form class is like this:

class SN4639(Form):
    time_offset = RadioField(u'Label', choices=[
        ('2', u'Check when Daylight saving has begun, UTC+02:00'),
        ('1', u'Check when Daylight saving has stopped, UTC+01:00')],
        default=2, validators=[Required()])

When I now open the edit form, I get via SQL the value 1 or 2 - how can I preset the specifiy radiobutton?

Upvotes: 17

Views: 12218

Answers (4)

Thales Ferraz
Thales Ferraz

Reputation: 1

My friend,

You need to fill in the .data field with the data that is in the database after instantiating the form. See that example:

my_instance = SN4639()
my_db_id = get_id_on_my_db()  # fill the variable with the database id

my_instance.time_offset.data = my_db_id  # here's the cat jump

Now, when you use my_instance.time_offset () in your HTML, the correct radio will be selected

IMPORTANTE NOTE:

If your id is an integer, you must add the parameter coerce=int in RadioField. See that example:

time_offset = RadioField(u'Label', choices=[
    (2, u'Check when Daylight saving has begun, UTC+02:00'),
    (1, u'Check when Daylight saving has stopped, UTC+01:00')],
    coerce=int,
    default=2, validators=[Required()])

Upvotes: 0

sparker
sparker

Reputation: 273

default=2 needs to be of type string, not int:

class SN4639(Form):
    time_offset = RadioField(u'Label', choices=[
        ('2', u'Check when Daylight saving has begun, UTC+02:00'),
        ('1', u'Check when Daylight saving has stopped, UTC+01:00')],
        default='2', validators=[Required()])

Upvotes: 12

davidism
davidism

Reputation: 127210

Form.__init__ takes a keyword argument obj= which will populate the form from the given object if no formdata or other defaults are provided. Pass the result from the database to that and it should work.

Upvotes: -1

Brandon W. King
Brandon W. King

Reputation: 208

If I understand your question properly, you want to have the form render with a pre-selected choice (rather than returning a default choice if no value is submitted to the form)...

What you can do is construct the form while setting the pre-selected value:

myform = SN4639(time_offset='2')

And then pass myform off to your template to be rendered.

Upvotes: 3

Related Questions