[Answered ]-Django Date formatting in forms query


You’ll need to create Date objects from your form data, which is currently a string. The error you’re getting is from django trying to compare those strings to the dates on the models.


from datetime import datetime

format = '%d-%m-%Y' # Or whatever your date format is
st = datetime.strptime(startdate, format)
ed = datetime.strptime(enddate, format)

data = MyModel.objects.filter(recorded_on__range=(st.date(), ed.date()))

Should point you in the right direction.


I am a bit confused about the error message (i.e. where does the error occur – when you make the query?).

However, I used this to convert a string from a url parameter to a datetime.date:

def things_by_appointment(request, appointment_date):
    Things with appointment date yyyy-mm-dd
        as_date = datetime.datetime.strptime( appointment_date, '%Y-%m-%d').date
    except ValueError:
        return HttpResponseBadRequest('%s is not a correct date' % appointment_date )

    things = Thing.objects.filter(
                              Q( appointment_date = as_date ),

Althoug the string is from the path and not from the query string, it should not make a difference.


Leave a comment