django timezone issue in a formset field

114 views Asked by At

A foreignkey object I'm using in a modelform shows up like this in the template:

enter image description here

It shows the leg's datetime in UTC, which is the default timezone. It needs to show the date information localized to the user's timezone. I assume it is using the following information from the model to render the Leg datetime information:

    def __unicode__(self):
    return  str(self.carpool.name) + " | " + str(self.drive_date_time)  + ' | to: ' + self.endpoint

I have a custom middleware that checks to see if a user is authenticated and, if so, sets the timezone to the user's timezone. It works fine on templates, but it doesn't seem to be working for this modelform.

How can I have the datetime information in this modelform show up with the current user's timezone, which is stored in my db and accessible at the template?

Thanks!

1

There are 1 answers

0
mb52089 On BEST ANSWER

I fixed it like this:

    def __unicode__(self):
    return  str(self.carpool.name) + " | " + str(self.drive_date_time.astimezone(pytz.timezone(self.carpool.drivers.all()[0].timezone)).strftime('%m/%d/%y: %I:%M %p'))  + ' | to: ' + self.endpoint