Custom choices in WTForms SelectField bsed on current date

1.1k views Asked by At

I would like to create a custom SelectField that provides different choices in based on the current date. For example, if it is the 13th of the month, the choices will be the values 1 through 13. How do I do this?

def register_extensions(app):
    security.init_app(app, datastore=ds, register_form=forms.ExtendedRegisterForm)

class ExtendedRegisterForm(RegisterForm):
    pay_month = SelectField(choices=[('need', 'custom'), ('day', 'choices')])
1

There are 1 answers

0
davidism On BEST ANSWER

Override the form's __init__ method and populate the field's choices with the range of values from 1 to the current day.

from datetime import datetime

class ExtendedRegisterForm(RegisterForm):
    pay_month = SelectField()

    def __init__(self, *args, **kwargs):
        super(ExtendedRegsiterForm, self).__init__(*args, **kwargs)
        now = datetime.utcnow()
        self.pay_month.choices = [(i, i) for i in range(1, now.day + 1)]