Problem with date validator

79 weergaven
Naar het eerste ongelezen bericht

felix

ongelezen,
23 sep 2015, 17:06:5423-09-2015
aan 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

ongelezen,
23 sep 2015, 17:44:2123-09-2015
aan 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

ongelezen,
24 sep 2015, 15:13:0124-09-2015
aan 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

ongelezen,
24 sep 2015, 16:18:2824-09-2015
aan 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

ongelezen,
2 nov 2015, 08:50:0502-11-2015
aan 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.
Allen beantwoorden
Auteur beantwoorden
Doorsturen
0 nieuwe berichten