1

I would like to use pendulum as a base datetime library with Django. So, a DateTimeField should work with pendulum objects, not datetime objects.

I have followed an example on pendulum's docs page and created a special field:

import pendulum
from django.db.models import DateTimeField as BaseDateTimeField


class DateTimeField(BaseDateTimeField):

    def value_to_string(self, obj):
        val = self.value_from_object(obj)

        if isinstance(value, pendulum.DateTime):
            return value.format('YYYY-MM-DD HH:mm:ss')

        return '' if val is None else val.isoformat()

...and used that in my models.py:

class Task(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    done = models.BooleanField()
    due_date = BaseDateTimeField()

    def is_today(self):
        return self.due_date.in_timezone('utc').date() == pendulum.today('utc').date()

...however I'm getting an error:

'datetime.datetime' object has no attribute 'in_timezone'

...which obviously means that Django treats due_date still as a datetime object, not a pendulum object.

Is there a possibility of switching to using pendulum as a base datetime library with Django?

P.S.

I think something is wrong with that docs snippet, value appears out of the blue, but I don't think that this is the cause of the problem.

adder
  • 3,512
  • 1
  • 16
  • 28
  • Looks like you forgot to use your custom field :) You have `due_date = BaseDateTimeField()` instead of `due_date = DateTimeField()` – Pierre V. Oct 26 '19 at 15:26
  • 1
    @PierreV. Yeah, you're right. I've corrected the mistake, still getting the error. – adder Oct 26 '19 at 15:31

0 Answers0