Darwin Tech
Darwin Tech

Reputation: 18919

Django Date formatting in forms query

Hi I have a model containing:

class MyModel(models.Model):
    id = models.IntegerField(primary_key=True)
    recorded_on = models.DateField()
    precipitation = models.FloatField(null=True, blank=True)

I have a form which looks like this:

class QueryForm(forms.Form):
    precipitation = forms.BooleanField(label=ugettext_lazy('Precipitation'),)   
    startdate = forms.DateField(widget = widgets.AdminDateWidget, label=ugettext_lazy('Start Date'),)
    enddate = forms.DateField(widget = widgets.AdminDateWidget, label=ugettext_lazy('End Date'),)

In my views.py I have one view for the form and a separate view for collecting the data via GET. This is very simplified version of the second view.py:

def results(request):
    if 'q' in request.GET:
    ...
    startdate = request.GET.get('startdate', None)
    enddate = request.GET.get('enddate', None)
    data = MyModel.objects.filter(recorded_on__range = (startdate, enddate))
    ...

My date variables in GET are of the format 'YYYY-MM-DD'.

The problem is that the query raises this error:

coercing to Unicode: need string or buffer, datetime.date found

What is the best way to deal with my date format to make the query?

Upvotes: 1

Views: 2201

Answers (2)

Gwilym Humphreys
Gwilym Humphreys

Reputation: 231

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.

so:

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.

Upvotes: 1

alex
alex

Reputation: 1229

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
    '''
    try:
        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.

Upvotes: 1

Related Questions