WTForms RadioField default values

10,034

Solution 1

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()])

Solution 2

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.

Share:
10,034

Related videos on Youtube

Kilrathy
Author by

Kilrathy

Simple Linux System Engineer

Updated on June 04, 2022

Comments

  • Kilrathy
    Kilrathy almost 2 years

    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?

    • Denis
      Denis almost 11 years
      If you want to set default at forms for which reasons are you want to do that in html? Do you want two default values?
    • Kilrathy
      Kilrathy almost 11 years
      At the creation form, I set defaults, as you can see, in the class. But now I'm creating a edit form and there it should be pre-selected. e.g. "male / female" and when I got the value 'm' from the db, male should be selected... How can I do this?
    • Denis
      Denis almost 11 years
      default=yourObjectFromDB.sex ????