0

I'm trying to pass input from a template to a query in my view, but if the date is not passed in Django's default date format YYYY-MM-DD then it throws an error.

[u"'11/11/2012' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]

template.html

<form method="GET" action="/BusComm/interactions">
    <div style="width: 100px; float:left">
        <p>To Date:</p>
    </div> 
    <div style="width: 200px; float:left">
        <input type="date" Placeholder="mm-dd-yyyy" name="date_to" id="id_q" value="{{ query }}" float="right">
    </div>
    <input type="submit" value="Submit" />
</form>

View.py

 def interactions(request):
    today = datetime.now().date()
    table = interactionsTable(Interactions.objects.all())

    if request.GET.get('date_from'):
            date_from = request.GET.get('date_from')

            table = interactionsTable(Interactions.objects.filter(date__range=[date_from, today]))
            return render(request, 'BusComm/interactions.html',{
            'table': table,
        })

The interactionsTable(Interactions.object.filter()) line is the one that throws the error.

My question is how can I change the date format in Django to accept MM/DD/YYYY instead of YYYY-DD-MM?

Ian Hoyos
  • 95
  • 1
  • 2
  • 8

1 Answers1

4
>>> from datetime import datetime
>>> d = datetime.strptime('11/11/2012', '%m/%d/%Y')
>>> d.strftime('%Y/%m/%d')
'2012/11/11'

Convert datetime format to YYYY-DD-MM in views.py is easier than force Django accept MM/DD/YYYY in filter.

Ykh
  • 7,567
  • 1
  • 22
  • 31