-
-
Save pije76/7b585d1e099705a7f01a8c09ac300fcc to your computer and use it in GitHub Desktop.
Getting user timezone from IP in Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pytz | |
from django.utils import timezone | |
.... | |
timezone.activate(pytz.timezone(user_time_zone)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from ipware.ip import get_real_ip | |
.... | |
ip = get_real_ip(request) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
.... | |
freegeoip_response = requests.get('http://freegeoip.net/json') | |
freegeoip_response_json = freegeoip_response.json() | |
user_time_zone = freegeoip_response_json['time_zone'] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserTimezoneMiddleware(object): | |
""" Middleware to check user timezone. """ | |
def process_request(self, request): | |
user_time_zone = request.session.get('user_time_zone', None) | |
try: | |
if user_time_zone is None: | |
freegeoip_response = requests.get('http://freegeoip.net/json/{0}'.format(ip)) | |
freegeoip_response_json = freegeoip_response.json() | |
user_time_zone = freegeoip_response_json['time_zone'] | |
if user_time_zone: | |
request.session['user_time_zone'] = user_time_zone | |
timezone.activate(pytz.timezone(user_time_zone)) | |
except: | |
pass | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment