Django ModelForm日期验证

时间:2013-11-13 18:30:21

标签: django forms validation model

使用默认的DateField()验证,您可以使用几种不同的格式来插入月,日和年。但是,我需要允许用户输入年份或月,日和年。

例如,在同一个字段中,您可以插入'5/10/2003'或'2003',验证将通过。另外,如果插入'2003',它是否必须默认为'1/1/2003'(或类似的东西),还是有更好的方法来做到这一点?

最后,这可以通过覆盖clean()方法在模型中完成,这样我就不必在多个表单中重用代码了吗?即:

class Project(models.Model):
    name = models.CharField(max_length=100)
    start_date = models.DateField()
    ## other fields

    def clean(self):
        # clean other fields as normal

        # override start_date

或者看起来应该是这样的:

def validate_date(value):
    """ Validate date to allow YYYY """
    ## Raise error on Validation fail

class Project(models.Model):
    name = models.CharField(max_length=100)
    start_date = models.DateField()
    ## other fields

    def clean(self):
        # clean other fields as normal

        # override start_date

1 个答案:

答案 0 :(得分:0)

documentation on creating custom form fields很稀疏,但这是可能的。

from django import forms


class MonthDateYearOrYearField(forms.DateField):
    def clean(self, value):
        date_length = len(value)

        if date_length == 4:  # 2003
            value = '1/1/{year}'.format(year=value)
        elif 8 <= date_length <= 10:  # 5/10/2003, 05/10/2003, 5/9/2009
            pass
        else:
            raise forms.ValidationError('date format must be "MM/DD/YYYY" or "YYYY"')

        return super(MonthDateYearOrYearField, self).clean(value)

class Project(forms.Form):
    start_date = MonthDateYearOrYearField()

elif条件可能需要一些工作,但你明白了。