Django custom field validator vs. clean

后端 未结 2 967
梦如初夏
梦如初夏 2021-02-01 06:34

I would like to create TodayOrLaterDateField() which would subclass DateField() field as I am using this condition in many places. The purpose of this field would be avoiding pu

相关标签:
2条回答
  • 2021-02-01 06:47

    Validators only validate, they don't return the improved format; Clean methods both validate and return a (sometimes amended) value.

    I think the way to go here is to just use a DateField with a validator as a inherited class of DateField with a default_validators set.

    import datetime
    from django.core import exceptions
    from django.db import models
    from django.utils.translation import ugettext_lazy as _
    
    def validate_date_today_or_later(value):
        'Place this in validators.py and import it to keep your model a bit cleaner'
        if value < datetime.date.today():
            raise exceptions.ValidationError(_('Date must be today or later'))
    
    class TodayOrLaterDateField(models.DateField):
        default_validators = [validate_date_today_or_later,]
    

    edit: You can apply the same validator to your form fields as well if you just want it there and not in your whole app.

    0 讨论(0)
  • 2021-02-01 06:54

    You can extend models.DateField and override to_python method. Didn't tested on Django 1.3 but should work.

    import datetime
    from django.core import exceptions
    from django.db import models
    
    class TodayOrLaterDateField(models.DateField):
        def to_python(self, value):
            value = super(TodayOrLaterDateField, self).to_python(value)
            if value < datetime.date.today():
                raise exceptions.ValidationError(u'Date must be today or later')
            return value
    
    0 讨论(0)
提交回复
热议问题