django-ninja
django-ninja copied to clipboard
Decoded datetime objects doesn't honor django timezone setting.
Is your feature request related to a problem? Please describe.
Decoded datetime objects are always timezone aware even if settings.USE_TZ is set to False.
When writing back these datetime objects to the db an error like the following is raised:
MySQL backend does not support timezone-aware datetimes when USE_TZ is False.
Describe the solution you'd like
To honor the django setting, datetime objects should be automatically converted to naive when settings.USE_TZ=False, for doing this it's possible to use the apposite utility from django.utils.timezone import make_naive.
Hi @fabiocaccamo
can you show some code where this can be reproduced ?
Hi @vitalik unfortunately I can't.
I try to submit a PR with tests.
I think I'm seeing this issue as well.
Say I have a Schema like:
class EventSchema(ModelSchema):
class Meta:
model = Event
fields = ["start"]
Where the model is:
class Event(Model):
start = models.DateTimeField()
With an API route something like:
@app.get('/events', response={200: List[EventSchema]})
def events(request):
return Event.objects.all()
Where 'start' is timezone aware, the output is not in the user's timezone. It is outputted in zulu time. When a request comes from a user with an active timezone set, I'd expect the response to be in the user's timezone, like when using Django templates.
I changed the schema to:
class EventSchema(ModelSchema):
@field_validator("start", check_fields=False)
def convert_to_localtime(cls, value):
return localtime(value)
class Meta:
model = Event
fields = ["start"]
This returns the user's local time in their selected timezone (2024-04-23T02:53:52.036-07:00 for PST), and not zulu time (2024-04-23T02:53:52.036Z for example). It falls back to the server timezone (settings.TIME_ZONE), which I always set to UTC.