3

In my form I have a DateField called booking_date that is rendered with the AdminDateWidget. The contents of the booking_date field needs to be internationalized. The problem appears when I want to use the value of the field in something like this:

booking = Booking.objects.get(booking_number='BN34D', booking_date='2010-11-21')

But if my date format is '%d.%m.%Y':

booking = Booking.objects.get(booking_number='BN34D', booking_date='21.11.2010')

I get a 'ValidationError: Enter a valid date in YYYY-MM-DD format'

How can I make the query regardless of the date format used?

3 Answers 3

4

You should parse it first with a localized version of the strftime format.

from datetime import datetime
d = datetime.strptime('...')
booking.objects.get(..., booking_date=d.date())

Use these formats in strptime:

http://linux.die.net/man/3/strftime

You shouldn't rely on passing directly from the user into the query.

Looks like you should be doing the following from your specific example:

d = datetime.strptime('%d.%m.%Y')
booking = Booking.objects.get(booking_nmber='BN34D', booking_date=d)
3
  • Sorry, I keep using wikimedia markup for codeblocks instead of markdown... fixed so its viewable
    – dlamotte
    Commented Feb 22, 2011 at 0:03
  • How can I know the date format? Is there a way to access this format?
    – Seitaridis
    Commented Feb 22, 2011 at 8:57
  • It would have been good to obtain this format using the current locale.
    – Seitaridis
    Commented Feb 22, 2011 at 9:04
1

As I understand your question, you don't know for sure in advance, which locale will be used. That can bring you into unsolvable problems. ("10-11-12" could be Oct 11, 2012 or Nov 12, 2010 or ...)

So you must have a limited, distinguishable set of possible formats. Then you can do:

POSSIBLE_FORMATS = ('%d.%m.%Y', '%Y-%m-%d', '...')

for f in POSSIBLE_FORMATS:
    try:
        d = datetime.date.strptime(date_str, f)
        break
    except ValueError:
        continue
    raise ValueError

booking = Booking.objects.get(booking_number='BN34D', booking_date=d)
2
  • In the formats.py file for german DATE_INPUT_FORMATS[0] will return '%d.%m.%Y' and for english DATE_INPUT_FORMATS[0] will return '%Y-%m-%d'. I always know that I want the first element, so there is no ambiguity.
    – Seitaridis
    Commented Mar 3, 2011 at 11:28
  • I am trying to solve this using FORMAT_MODULE_PATH: stackoverflow.com/questions/5165634/…
    – Seitaridis
    Commented Mar 3, 2011 at 12:01
1

I have solved the problem using this:

from django.utils import formats

formats.get_format('DATE_INPUT_FORMATS')[0]

This format is then used for parsing the date like xyld showed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.