我有一个带有初始end_date的表单。我遇到了值(value)错误,因为今年是year年,而我们目前处于2月。

我的代码的结束日期为30,但是我在弄清楚如何编写将发现是否为a年的代码以及将初始end_date设置为2月的最后一天时遇到了麻烦。

这是我的form.py,用于控制end_date的初始值

class MaturityLetterSetupForm(forms.Form):
def __init__(self, *args, **kwargs):
    from datetime import datetime
    today = datetime.today()
    start_year = today.year
    start_month = today.month
    start_date = datetime(start_year, start_month, 1)
    try:
        end_date = datetime(start_year, start_month, 30)
    except ValueError:
        end_date = datetime(start_year, start_month, ?)

    super(MaturityLetterSetupForm, self).__init__(*args, **kwargs)
    self.fields['start_date'] = forms.DateField(initial=start_date.strftime("%B %d, %Y"),
        widget=forms.TextInput(attrs={'class':'datepicker', 'value': today }))

    self.fields['end_date'] = forms.DateField(initial=end_date.strftime("%B %d, %Y"),
        widget=forms.TextInput(attrs={'class':'datepicker', 'value': today }))

编辑
与@Paul交谈后
我的初始化成为:
def __init__(self, *args, **kwargs):
    from datetime import datetime
    import calendar
    today = datetime.today()
    start_year = today.year
    start_month = today.month
    start_date = datetime(start_year, start_month, 1)
    if calendar.isleap(start_year) and today.month == 2:
        end_date = datetime(start_year, start_month, calendar.mdays[today.month]+1)
    else:
        end_date = datetime(start_year, start_month, calendar.mdays[today.month])
    super(MaturityLetterSetupForm, self).__init__(*args, **kwargs)
    self.fields['start_date'] = forms.DateField(initial=start_date.strftime("%B %d, %Y"),
        widget=forms.TextInput(attrs={'class':'datepicker', 'value': today }))

    self.fields['end_date'] = forms.DateField(initial=end_date.strftime("%B %d, %Y"),
        widget=forms.TextInput(attrs={'class':'datepicker', 'value': today }))

查找当前月份的最后一天。

最佳答案

calendar.isleap(year)怎么样?

另外,请勿使用try/except来处理此问题,而应使用if条件。就像是:

if calendar.isleap(year):
    do_stuff
else:
   do_other_stuff

关于python - 找出是否是a年,并进行相应设置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9131293/

10-12 23:30