Creating Django Queries with Localized Dates

In my form, I have a DateField called booking_date, which is displayed using AdminDateWidget. The contents of the book_date field must be internationalized. The problem occurs when I want to use a field value 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 "ValidationError: enter a valid date in the format YYYY-MM-DD"

How can I make a request regardless of the date format used?

+3
source share
3 answers

I solved the problem using this:

from django.utils import formats

formats.get_format('DATE_INPUT_FORMATS')[0]

This format is then used to parse the date, for example xyld .

+1

strftime.

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

strptime:

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

.

, :

d = datetime.strptime('%d.%m.%Y')
booking = Booking.objects.get(booking_nmber='BN34D', booking_date=d)
+4

As I understand your question, you do not know for sure in advance which language will be used. This can lead to insoluble problems. ("10-11-12" may be October 11, 2012 or November 12, 2010 or ...)

So, you should 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)
+1
source

Source: https://habr.com/ru/post/1793722/


All Articles