Saturday, January 21, 2017

Django and timezones ... how to initialize a field to now() in the in clients time zone?

I have a model with this field:

date_time = models.DateTimeField(default=timezone.now)

if I look at the generic create form, it inializes the date_time field with now in UTC, not in local time.

Now I appreciate there are two things at play here:
  1. the desired UX is to see now in my time zone.
  2. Django, running on the server has no idea what my time zone is.
Now I can think my way through this and find some solutions, not short of imagination here. But as I work on nutting one out, I am struck, as ever, with the notion that 1. is surely a ubiquitous use case ... namely I cannot seriously be the first person to have this desire or tackle this problem and is there not a stock standard approach in Django to doing this?

As I read it I can find the time zone in Javascript at the client side:

This works fine for example:

    var tz_name = jstz.determine().name();
   
var tz_offset = new Date().getTimezoneOffset()/60;

giving me pleasing results (though I appreciate, before anyone points it out, that pleasing results are by no means guaranteed as it as it is premised on the correct TZ configuration of the client computer among other things, but the application in mind does not REQUIRE time accuracy (am just logging events that happened at a given time and timezone errors are of no practical data integrity or security concerns for a few good reasons) .

And I can submit these in hidden fields too.

But the obvious solution, which I find a tad kludgy alas is at the client side in JS to find the date_time input field, and adjust it's value from UTC to local time. Right now it's presenting as UTC.

Even if I could find a way to ask Django to use a different timezone (tmiezone.activate) it won't kow what Timezone until it's heard from the client. And it's not in HTTP headers alas, though someone thinks it should be:

On submission of course as I can submit the TZ info in hidden fields it should be easy to convert the submission back to UTC for saving into the database.

Still, I wonder openly, is this not long solved, more elegantly?

Regards,

Bernd.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4738d161-186d-4205-a148-1f17e5d231ef%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment