Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django 1.4 how to automatically get user's timezone from client

I would like to know if there is a way to automatically retrieve user's timezone from client. Especially during login.

I tried to add this in the login page (using auth.login):

{% get_current_timezone as TIME_ZONE %}

and then add this in the login form

<input type="hidden" name="next" value="/redirect/?tz={{ TIME_ZONE }}">

but tz is always the timezone of the server.

like image 546
xpanta Avatar asked Apr 19 '12 20:04

xpanta


People also ask

How do I get Django time zone?

The solution to this problem is to use UTC in the code and use local time only when interacting with end users. Time zone support is disabled by default. To enable it, set USE_TZ = True in your settings file. In Django 5.0, time zone support will be enabled by default.

Which function allows you to find the users time zone?

You can set any specific time zone using the PHP function date_default_timezone_set . This sets the specified time zone for users. Basically the users' time zone is goes to the client side, so we must use JavaScript for this.

What does timezone NOW () return?

timezone. now() useful. This function returns the current date and time as a naive datetime when USE_TZ = False and as an aware datetime when USE_TZ = True .

Is Django Datetimefield timezone aware?

Django stores datetime information in UTC in the database, uses timezone-aware datetime objects internally, and translates them to the end user's time zone in templates and forms.


3 Answers

I've simplified it even further, and you can plug in in here: https://github.com/Miserlou/django-easy-timezones or http://gun.io/blog/django-easy-timezones/

like image 138
Rich Jones Avatar answered Sep 25 '22 06:09

Rich Jones


From the documentation:

Selecting the current time zone

The current time zone is the equivalent of the current locale for translations. However, there's no equivalent of the Accept-Language HTTP header that Django could use to determine the user's time zone automatically. Instead, Django provides time zone selection functions. Use them to build the time zone selection logic that makes sense for you.

You can try setting timezone cookie via javascript by utilizing getTimezoneOffset function or try to do some geoip magic and figure timezone by location. Probably the most reliable way would be to ask the user directly and save this information in user profile/session.

like image 22
BluesRockAddict Avatar answered Sep 25 '22 06:09

BluesRockAddict


I was hunting around for the sam thing yesterday. In the end I ended up putting together a Django app to what BluesRockAddict suggests above (i.e. use getTimezoneOffset):

https://github.com/adamcharnock/django-tz-detect

I hope someone finds that useful.

like image 43
Adam Charnock Avatar answered Sep 25 '22 06:09

Adam Charnock