Problem with date validator

已查看 80 次
跳至第一个未读帖子

felix

未读,
2015年9月23日 17:06:542015/9/23
收件人 django...@googlegroups.com

When today's date is entered in the form  it shows a form error saying that this date (today) is in the future.
What is wrong with the validator I'm using to allow dates until today?

models.py

...
import datetime

...

class SolicitudBase(models.Model):
    ....
    fecha = models.DateField(validators=[MaxValueValidator(datetime.date.today(), message="This date can't be in the future")])
    ....


I'm using Mysql and the following settings in my django project related to timezone are commented:

#TIME_ZONE = 'EST'
#USE_TZ = True

My server (debian 7) is using US/Eastern timezone.

and right now:
root@webapp:~# date
Wed Sep 23 17:04:36 EDT 2015

Thanks in advance,
Felix.

Simon Charette

未读,
2015年9月23日 17:44:212015/9/23
收件人 Django users
Hi Felix,

The way you create your validator instance it is passed the
value returned by `date.today()` at module initialization time.
That is when the Python process starts.

It means that if you started your development server or say
a gunicorn process on your server yesterday the max value
the value will compare against will be yesterday and not the
actual date which is what I'm assuming you're trying to do
here.

Instead of relying on MaxValueValidator I suggest you write
your own by simply defining the following function and
passing in your field validators list.

def validate_past_date(value):
    if value > datetime.date.today():
      raise ValidationError('This date can't be in the future')

Cheers,
Simon

felix

未读,
2015年9月24日 15:13:012015/9/24
收件人 django...@googlegroups.com
El 23/09/15 17:12, felix escribió:
Thanks Simon for your suggestion.
I forgot to mention that it only happens with the present date (today) but it doesn't happen with past dates. So it makes me think it could be a time zone issue.

Cheers,
Felix.

Simon Charette

未读,
2015年9月24日 16:18:282015/9/24
收件人 Django users
Hi Felix,

From what I know model and form DateField are completely TIME_ZONE agnostics.

This is not the case for DateTimeField however. Is this what you're using?

Simon

felix

未读,
2015年11月2日 08:50:052015/11/2
收件人 django...@googlegroups.com
El 24/09/15 15:18, felix escribió:
You were right Simon.
Using a custom validator instead of MaxValueValidator for dates solved my issue.

....
def validate_not_future_date(value):
    if value > datetime.date.today():
        raise ValidationError('%s is in the future' % value)

....
class SolicitudBase(models.Model):
    ....
    fecha = models.DateField(validators=[validate_not_future_date])



Thanks.
回复全部
回复作者
转发
0 个新帖子