Django中如何按事件时区显示Meeting的started_on时间?
Got it, let's get those meeting times showing up in the event's timezone instead of your local one. Here's how to make your started_on_tz method work perfectly in your templates:
Step 1: (Optional but Cleaner) Turn the Method into a Property
First, I'd recommend converting your started_on_tz method into a Python property—this makes it feel more like a regular field when you use it, no need for parentheses in templates. Update your Meeting model like this:
from django.utils import timezone class Meeting(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) started_on = models.DateTimeField() ended_on = models.DateTimeField() @property def started_on_tz(self): # Add a fallback in case the event has no timezone set if not self.event.time_zone: return self.started_on return self.started_on.astimezone(timezone(self.event.time_zone))
Step 2: Update Your Template to Use the Timezone-Aware Value
In your template where you were displaying {{ meeting.started_on }}, just replace it with {{ meeting.started_on_tz }}. You can also add Django's date filter to format it nicely, like:
<!-- Example template code --> <div class="meeting-time"> Started on: {{ meeting.started_on_tz|date:"F j, Y, g:i A" }} </div>
Adjust the date format string ("F j, Y, g:i A") to match your desired display style—Django has tons of formatting options for dates and times.
Key Checks to Avoid Issues
- Make sure
event.time_zonestores a valid timezone identifier (like"America/Los_Angeles"or"Europe/London"), not just an offset like-0800. Thetimezone()function relies on these standard identifiers. - Confirm that
started_onis indeed timezone-aware (you mentioned it is, but double-check—if your project usesUSE_TZ = Truein settings, DateTimeFields are timezone-aware by default).
That's it! Your meetings will now show up in the timezone linked to their parent event instead of your server's local timezone.
内容的提问来源于stack exchange,提问作者Atma

