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

15,638

You haven't shown the full code, but I suspect the problem is with your model's __unicode__ method. This needs to return an actual unicode string - if you are just doing return self.recorded_on that will fail with the given error. Try something like return unicode(self.recorded_on), or use strftime to convert to your desired date formatting, for example self.recorded_on.strftime('%Y-%m-%d').

Share:
15,638
Darwin Tech
Author by

Darwin Tech

Updated on July 13, 2022

Comments

  • Darwin Tech
    Darwin Tech over 1 year

    I have a model:

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

    in my views I have a query thus:

    import datetime
    
    def my_view(request):
        ...
        format = '%Y-%m-%d' 
        sd = datetime.datetime.strptime(startdate, format)
        ed = datetime.datetime.strptime(enddate, format)
        queryset = MyModel.objects.filter((recorded_on__range = (sd, ed)))
        ...
    

    But whenever I try and do anything with the queryset (e.g. json dump, display in template), I get the following error:

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

    I know there must be an easy way to deal with this, but I have not yet found it.

    Any help would be much appreciated.

    EDIT:

    An example of data:

    +----+-------------+---------------+
    | id | recorded_on | precipitation |
    +----+-------------+---------------+
    | 24 | 1987-07-02  |          20.7 |
    | 33 | 1987-07-11  |           0.4 |
    +----+-------------+---------------+
    
  • Darwin Tech
    Darwin Tech over 11 years
    Perfect. Thankyou. I actually had no idea the problem could be with the model!