John
John

Reputation: 4261

How to handle date in Django?

I am displaying the date to the user, on a search form, in 'dd/mm/yyyy' format, using the jquery datepicker. My target audience is British. But, when I try to use this date for a query on a model with DateField, I get this exception

Enter a valid date in YYYY-MM-DD format.

So, how should I handle this scenario?

Upvotes: 1

Views: 1116

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174614

You have two choices.

Use a form.DateField - which will normalize to a date time object that you can use directly in your query. Just assign the jquery object to the date field:

<script type="text/javascript">
 $(function() {
        $("#id_MyDateField").datepicker({ dateFormat: 'dd/mm/yy' });

 });
</script>

Convert the date manually:

form_date = request.GET.get('the_date',datetime.datetime.now()) # defaults to now
db_date = datetime.datetime.strptime(form_date,'%d/%m/%y')

Then use db_date in your query

Upvotes: 4

Chris Morgan
Chris Morgan

Reputation: 90732

Enter a valid date in YYYY-MM-DD format.

In other words, transform the date from one format to the other.

Upvotes: 0

Related Questions