简体   繁体   English

当前日期在WTForms SelectField中的自定义选择

[英]Custom choices in WTForms SelectField bsed on current date

I would like to create a custom SelectField that provides different choices in based on the current date. 我想创建一个自定义的SelectField ,它根据当前日期提供不同的选择。 For example, if it is the 13th of the month, the choices will be the values 1 through 13. How do I do this? 例如,如果是每月的13号,则选择的值将是1到13。我该如何做?

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

Override the form's __init__ method and populate the field's choices with the range of values from 1 to the current day. 覆盖表单的__init__方法,并使用从1到当天的值范围填充字段的choices

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM