Reputation: 1683
I want to add a models.TimeField
field to my Django table.
And restrict the user so that he can only add a round hour (e.g. 13:00 but not 13:30).
What is the best way to do this?
Upvotes: 3
Views: 485
Reputation: 477676
You can define an extra validator [Django-doc]:
from django.core.exceptions import ValidationError
def validate_round_hour(value):
if not value.minute == value.second == value.microsecond == 0:
raise ValidationError(
'This should be a round hour.',
params={'value': value},
)
then you can add the validiator to your model field:
class SomeField(models.Model):
some_time = models.TimeField(validators=[validate_round_hour])
Note that this will not be enforced at the database level. But a form will run the validators, and thus can prevent a user entering invalid data.
Upvotes: 1