Apostolos
Apostolos

Reputation: 8111

datetime fields are saved with different values and show different values in forms django

I have a model that has a DateTimeField in it.

class Event(models.Model):
    .....
    date = models.DateTimeField()

and a model form for this event

class EventForm(ModelForm):

    class Meta:
        model= Event

When I create an event from admin I set the time to the time I want the event to occure, let's say 19:30. But if I call the events.date property I get

event.date
datetime.datetime(2013, 11, 20, 17, 30, tzinfo=<UTC>)

If I use it in a template like

{{event.date.hour}}:{{event.date.minute}}

it shows 17:30.

But when i load it on template within the model form

event_form = EventForm(instance=event)

and in template

{{event_form.as_p}}

then the date renders the same as I added it in the admin page, that is 19:30

How can I change this behavour. Does django always save in UTC the dates? I am in Greece hence the minus 2 hours (I think) of the datetime object. Supposingly my app will run in many different countries, can I automate this, like when I render the date on a template using the property it will show the time that was actually saved and not the time in UTC. Hope I am making sense....

In my settings file i have

TIME_ZONE = 'Europe/Athens'
USE_TZ = True

Upvotes: 0

Views: 345

Answers (1)

Rohan
Rohan

Reputation: 53386

If you want time zone per user, you need to store that in your user profiles or something like that. And then use that information to convert user entered time to appropriate UTC to store.

Without that you are storing the times as per the timezone set on your server. So if some user in GMT, selects time as 0800, it will be actually 0800 in Athens not in GMT.

In template you can do

{% load tz %}

{% timezone get_current_users_timezone %}
    {{ event.date }}
{% endtimezone %}

Refer django timezones for details info.

Upvotes: 2

Related Questions