still.Learning still.Learning - 1 year ago 85
Python Question

Set minimum value for a DateTimeField

I have a Django form with a DateTimeField model, and I was wondering if there is a way to make sure that the date/time the user enters is always greater than the current time.

This is what I have in my form:

from django.db import models
from django import forms
import datetime

start_time = models.DateTimeField(,
help_text='Format is: yyyy-mm-dd hh:mm:ss',

Answer Source

add this to your model.

from django.core.exceptions import ValidationError
from django.db import models

class MyModel(models.Model):
    # ...
    # extend the validation
    def clean(self, *args, **kwargs):
        # run the base validation
        super(MyModel, self).clean(*args, **kwargs)

        # Don't allow dates older than now.
        if self.start_time <
            raise ValidationError('Start time must be later than now.')