What Is The Best Practice To Validate A Django Datefield At The Model Level As Particular Day Of The Week?
Solution 1:
I would go with providing a validator, especially if you need a clean DB when inputting data without a form.
If the input is a datetime.date
, you can just use mydate.weekday()
to get its day of week. It should be '5' for Saturday.
Something like:
defvalidate_saturday(value):
ifnot value.week.weekday == 5:
raise ValidationError("Date should be a Saturday.")
An alternative might be to specify the week number in your models instead of a DateField.
Solution 2:
You can specify a validator on the field
week = models.DateField(validators=[validate_sat])
defvalidate_sat(value):
if value is not a saturday:
raise ValidationError('%s isn't a saturday' % value)
I've left out the actual logic to work out what day of a week the date is but that shouldn't be too difficult
Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form
Now since you say you may not use forms in all instances of saving, you may want to use a pre_save
signal that will do the validation, you can always raise the validation error in this if it isn't a valid value.
If at all possible, it might be worth trying to consolidate your model updating methods to update from forms.
Post a Comment for "What Is The Best Practice To Validate A Django Datefield At The Model Level As Particular Day Of The Week?"