Django timezone problem

375 views
Skip to first unread message

Mikko Meronen

unread,
Feb 3, 2019, 7:00:30 PM2/3/19
to django...@googlegroups.com
Hi,

Is there any easy way in Django to catch end user's local time when end user access the webpage?

I have read django documentation and tried to google solutions, but I get quite confused. Below you will find my code. In short the code should show a story on my webpage what happened in the past on the current day. However it doesn't take into account the endusers local time, and thus doesn't work properly.


Views.py
from django.utils import timezone

t = timezone.now()     [This should somehow react to endusers local time]
dm = t.strftime('%m-%d')
history = history.objects.filter(monthday__exact=dm)
historystory = random.sample(list(history), 1)
args = {'historystory':historystory}
return render(request, "news/home.html", args)

home.html
[in html I have just the basic things to show the content]

<div class="card">
            <div class="card-body">
                {% for x in historystory %}
    <h4 class="card-text"> {{ x.title }} </h4>
        <h4 class="card-text"> {{ x.subtitle }} </h4>
    <p class="card-text"> {{ x.content }} </p>
    {% endfor %}
        </div>
</div>


Settings.py
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

You can check my webpage (http://www.topithenewsdoggy.com/) to get better understanding what I'm doing. The part is under Additional info.

-Mikko

Waqas Ali

unread,
Feb 3, 2019, 7:09:37 PM2/3/19
to django...@googlegroups.com
Plz can you share the all data about this site and source code

--
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...@googlegroups.com.
To post to this group, send email to django...@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/CAGD0jj%2Bh_1Pd50eE0e0zXt8P-yozqCnZeYYXTe6bj6Tt6UopxA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Amitesh Sahay

unread,
Feb 4, 2019, 8:15:55 AM2/4/19
to django...@googlegroups.com
Hello Mikko,

There are basically two ways which I know . One is the timezone module that you are using another is datetime module. I believe that timezone module is more effective one.
But instead of calling timezone.now() , call timezone.now.

Or what is the exact issue are you facing?

Regards,
Amitesh Sahay
91-750 797 8619


--

Mikko Meronen

unread,
Feb 4, 2019, 2:05:10 PM2/4/19
to django...@googlegroups.com
Hi,

Thank you for your answer. I tried timezone.now without parentheses, but it gave me server error. I have also tried datetime, but I face the same issue.

The issue I have:
I want people to see what happened today in the past. So I created a database where is a story or stories what happened in the history on this day(date). My view should be able to pick a right story from the database based on the users timezone. If Australian visits my webpage at this moment, he should be able to see what happened on February 5 in the past (it's already February 5 there). However he sees what happened on February 4, because it is February 4 here (in Finland or England, not sure what timezone I'm using). So I want to make my view to understand the end user's local time, so it can pick the right story from the database for the webpage visitor.

-Mikko

Andréas Kühne

unread,
Feb 6, 2019, 4:47:24 PM2/6/19
to django...@googlegroups.com
Hi Mikko,

The best way to do this is actually to set the timezone for the user via a property on the user. The reason for this is that there is no way to actually get the timezone from the browser (at least not completely correctly). That being said, if you want to go down that route - try something like this: https://github.com/adamcharnock/django-tz-detect

What it does is use javascript to get the timezone (which doesn't always return the right timezone) and then uses a middleware to set the timezone for the current user. That way you will get the information in the correct timezone for the user according to the browser (which might not be correct).

Regards,

Andréas


Mikko Meronen

unread,
Feb 6, 2019, 8:25:45 PM2/6/19
to django...@googlegroups.com
Hi,

Thank you for your help :)

-Mikko

Thomas Lockhart

unread,
Feb 6, 2019, 11:02:31 PM2/6/19
to django...@googlegroups.com
If you want this to happen without the user registering and giving you an address, you could use a geolocation and ip address database. I think yahoo and google both provide these services (I used yahoo because their terms of service were less restrictive). If the user allows the browser to report a location, use that. Or if not then use the apparent IP address to estimate a time zone. Neither are fool proof and in particular a casual user to your site will likely be put off by the browser asking to share the location.

hth

- Tom

Amitesh Sahay

unread,
Feb 7, 2019, 5:30:38 AM2/7/19
to django...@googlegroups.com
Hello Mikko, 

Below is a sample from my models.py

class Listings(models.Model):
realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=200)
address = models.CharField(max_length=200)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
zip_code = models.CharField(max_length=20)
description = models.TextField(max_length=200, blank=True)
price = models.IntegerField()
bedrooms = models.IntegerField()
bathrooms = models.DecimalField(max_digits=2, decimal_places=2)
garage = models.IntegerField(default=0)
sqft = models.IntegerField()
lot_size = models.DecimalField(max_digits=5, decimal_places=1)
photo_main = models.ImageField(upload_to='photos/%y/%m/%d/')
photo_1 = models.ImageField(upload_to='photos/%y/%m/%d/', blank=True)
photo_2 = models.ImageField(upload_to='photos/%y/%m/%d/', blank=True)
photo_3 = models.ImageField(upload_to='photos/%y/%m/%d/', blank=True)
is_published = models.BooleanField(default=True)
list_date = models.DateTimeField(default=timezone.now, blank=True)
If you see in the above fields, "list_data" field has "timezone.now" without parenthesis. It is working for me. However, you can paste the code that you have written, so that people could debug.

Regards,
Amitesh Sahay
91-750 797 8619

Alvaro Chen

unread,
Feb 8, 2019, 8:04:19 PM2/8/19
to Django users

Set the timezone for the user via a property on the user is the best way. Otherwise, JS can detect the user's time zone. Use moment.js (https://momentjs.com/timezone/docs/#/using-timezones/guessing-user-timezone/) or Intl (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat).

In my project, JS sends an AJAX request to Django with timezone when anonymous users access the webpage. Save timezone in request.session.

from django.utils import timezone

import pytz

# Set user's timezone
tzinfo = pytz.timezone(request.session['timezone']) #request.session['timezone'] = 'America/Los_Angeles'
timezone.activate(tzinfo)
timezone.localtime(timezone.now()).isoformat()

# Resume default timezone (setting.py # TIME_ZONE)
timezone.deactivate()
timezone.localtime(timezone.now()).isoformat()
Hope this helps.

BR,

Alvaro

Mikko Meronen

unread,
Feb 8, 2019, 8:50:56 PM2/8/19
to django...@googlegroups.com
Hi Alvaro,

If I do that (JS and AJAX), do you think my views.py is already correct? T = timezone.now() is important for me in order to get the right data from sql for the end user. 

Views.py
from django.utils import timezone

t = timezone.now() [this should detect end user's timezone]    
dm = t.strftime('%m-%d')
history = history.objects.filter(monthday__exact=dm)
historystory = random.sample(list(history), 1)
args = {'historystory':historystory}
return render(request, "news/home.html", args)

-Mikko

-Mikko

Josiah Jenson Nawaya

unread,
Feb 8, 2019, 9:10:34 PM2/8/19
to django...@googlegroups.com
Hi, i believe what the system do with your timezone.now() function call is ton currently get the timezone of the location where your server is located. So if your hosting server is in England, it gets the server location timezone. U will need to first find a way to get the visitors location and get the  timezone at that location. Hope it helps

Perchouli

unread,
Feb 8, 2019, 9:17:52 PM2/8/19
to django...@googlegroups.com
Hi Mikko,

t = timezone.now()  just get UTC timezone when USE_TZ=True.
Modify as follows:

    tzinfo = pytz.timezone('end user's timezone')
    timezone.activate(tzinfo)
    t = timezone.localtime(timezone.now())



Mikko Meronen

unread,
Feb 8, 2019, 9:20:25 PM2/8/19
to django...@googlegroups.com
Hi,

But if  I get the visitor's timezone using JS and send it to Django using AJAX and also do the changes below Alvaro suggested:
from django.utils import timezone

import pytz

# Set user's timezone
tzinfo = pytz.timezone(request.session['timezone']) #request.session['timezone'] = 'America/Los_Angeles'
timezone.activate(tzinfo)
timezone.localtime(timezone.now()).isoformat()

# Resume default timezone (setting.py # TIME_ZONE)
timezone.deactivate()
timezone.localtime(timezone.now()).isoformat()

Do you think it should then be alright and my timezone.now() function works?

-Mikko



Reply all
Reply to author
Forward
0 new messages