Giter Site home page Giter Site logo

miserlou / django-easy-timezones Goto Github PK

View Code? Open in Web Editor NEW
202.0 6.0 44.0 22.92 MB

Easy timezones for Django based on GeoIP

Home Page: http://gun.io/blog/django-easy-timezones/

License: Apache License 2.0

Python 99.84% Shell 0.16%
python timezone django geoip easy-timezones easy easy-to-use automatic

django-easy-timezones's Introduction

Timezones. Yuck.

django-easy-timezones Build Status

Easy IP-based timezones for Django (>=1.7) based on MaxMind GeoIP, with IPv6 support.

Quick start

  1. Install django-easy-timezones

    pip install django-easy-timezones
  2. Add "easy-timezones" to your INSTALLED_APPS setting like this:

    INSTALLED_APPS = (
      ...
      'easy_timezones',
    )
  3. Add EasyTimezoneMiddleware to your MIDDLEWARE_CLASSES

    MIDDLEWARE_CLASSES = (
      ...
      'easy_timezones.middleware.EasyTimezoneMiddleware',
    )
  4. (Optionally) Add a path to the MaxMind GeoIP cities databases (direct link because I'm nice) in your settings file:

    GEOIP_DATABASE = '/path/to/your/geoip/database/GeoLiteCity.dat'
    GEOIPV6_DATABASE = '/path/to/your/geoip/database/GeoLiteCityv6.dat'
  5. Enable localtime in your templates.

    {% load tz %}
        The UTC time is {{ object.date }}
    {% localtime on %}
        The local time is {{ object.date }}
    {% endlocaltime %}
  6. Twist one up, cause you're done, homie!

Signals

You can also use signals to perform actions based on the timezone detection.

  1. To hook into the Timezone detection event to, say, save it to the request's user somewhere more permanent than a session, do something like this:

    from easy_timezones.signals import detected_timezone	
    
    @receiver(detected_timezone, sender=MyUserModel)
    def process_timezone(sender, instance, timezone, **kwargs):
    	if instance.timezone != timezone:
        	instance.timezone = timezone
        	instance.save()

django-easy-timezones's People

Contributors

caxap avatar craiglabenz avatar davegaeddert avatar doppins-bot avatar mskrajnowski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

django-easy-timezones's Issues

UTC time doesn't work

I am using your plugin to provide localised timezone in my app. The problem I am facing however is that all the times are converted to local timezone.

<tbody>
        {% for object in object_list %}
          <tr>
            <th>title</th>
            <td>{{ object.title }}</td>
          </tr>
          <tr>
            <th>Content</th>
            <td>{{ object.content }}</td>
          </tr>
          <tr>
            <th>tags</th>
            <td>{{ object.tags }}</td>
          </tr>
          <tr>
            <th>User</th>
            <td>{{ object.user }}</td>
          </tr>
           <tr>
            <th>Time</th>
            <td>
              {% load tz %}
              The UTC time is {{ object.time }}
              {% localtime on %}
                The local time is {{ object.time }}
              {% endlocaltime %}
            </td>
          </tr>
        {% endfor %}
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'newco.apps.clients',
    'newco.apps.profiles',
    'newco.apps.posts',
    'newco.apps.dashboard',
    'rest_framework',
    'easy_timezones',
    'south',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'easy_timezones.middleware.EasyTimezoneMiddleware',
)

I have used the same code as you have done.

Here is a demo in place as well. http://newco.herokuapp.com/posts/list/

Can you please help me with this. Does the middleware change all the time to timezone even if they are not inside the {% localtime on %} tag.

Exception Value: Invalid database type, expected City

I am using the version 0.6.2 and the GeoIP databases provided in the repository but I am getting this error ?
File "/home/alpha/.virtualenvs/cybrhome-alpha/lib/python2.7/site-packages/easy_timezones/middleware.py" in process_request

  1.                     tz = db.time_zone_by_addr(ip)
    
    File "/home/alpha/.virtualenvs/cybrhome-alpha/lib/python2.7/site-packages/pygeoip/init.py" in time_zone_by_addr
  2.         raise GeoIPError(message)
    

ImproperlyConfigured: GEOIP_DATABASE setting is defined, but file does not exist.

I am having problem when pushing new app with django-easy-timezones. Basicly, I need to call manage.py collectstatic to put files GeoLiteCityv6.dat and GeoLiteCity.dat to static directory. But when I run manage.py collectstatic, following error is raised.

remote: django.core.exceptions.ImproperlyConfigured: GEOIP_DATABASE setting is defined, but file does not exist.
remote: ln: creating symbolic link `/var/lib/openshift/user/app-root/runtime/repo//wsgi/static/media': No such file or directory

Neverending cycle.

I also have a suggestion. Instead of a need to update geoip database manually, how about using https://github.com/futurecolors/django-geoip ?

error: illegal IP address string passed to inet_pton

I get this error when bots are trying to access my django site. Any idea how illegal IP address should be dealt with?
Internal Server Error: /
Traceback (most recent call last):
File "/var/lib/openshift/5409d566e0b8cd8c7a0002b6/python/virtenv/lib/python2.7/site-packages/django/core/handlers/base.py", line 87, in get_response
response = middleware_method(request)
File "/var/lib/openshift/5409d566e0b8cd8c7a0002b6/python/virtenv/lib/python2.7/site-packages/easy_timezones/middleware.py", line 42, in process_request
tz = db.time_zone_by_addr(ip)
File "/var/lib/openshift/5409d566e0b8cd8c7a0002b6/python/virtenv/lib/python2.7/site-packages/pygeoip/init.py", line 583, in time_zone_by_addr
ipnum = util.ip2long(addr)
File "/var/lib/openshift/5409d566e0b8cd8c7a0002b6/python/virtenv/lib/python2.7/site-packages/pygeoip/util.py", line 39, in ip2long
return int(binascii.hexlify(socket.inet_pton(socket.AF_INET6, ip)), 16)
error: illegal IP address string passed to inet_pton

Detected timezone not saved in session

Hi

I'm reading through the code, which isn't even that big, but I can't find where the detected tz is saved into the session. I've been running some tests and it looks like it isn't saved. I find it confusing that the middleware is using request.session.get('django_timezone'), but never setting a key with that name. Or am I just dumb and missing something?

I could use a signal, but that sends me the user's instance, not the request. Also, I need to do stuff with that session value in a view, and I'm not really sure if django signals are synchronous.

Would it be possible to "fix" this? Or is this the intended behavior?

Local time is unaffected...

Using django 1.8.6, {% localtime on %} doesn't do anything! UTC time and localtime are the same. When USE_TZ = True, {% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }} yields America/Chicago while I'm currently in US/Mountain. Also, all dates in my templates are changed to fit the time zone, not just the dates inside of {% localtime on %}. Also, it's only yielding America/Chicago.

When USE_TZ = False, all dates are yielded in UTC time.

I also tried
TIME_ZONE = 'UTC'
and deleting TIME_ZONE from settings.py.

This package looks super useful. I'm probably missing something simple.

Not working with Django 1.11.5

After installing and setting up django with the easy-timezones and
"GET /with_tz/ HTTP/1.1" 200 - returns "UTC"
"GET /without_tz/ HTTP/1.1" 200 -returns "UTC"

Problem with installation

Running pip install django-easy-timezones is resulting in the following error:
Downloading/unpacking django-easy-timezones
Running setup.py (path:/tmp/pip-build-qTh9qM/django-easy-timezones/setup.py) egg_info for package django-easy-timezones
Traceback (most recent call last):
File "", line 17, in
File "/tmp/pip-build-qTh9qM/django-easy-timezones/setup.py", line 12, in
with open(os.path.join(os.path.dirname(file), 'requirements.txt')) as f:
IOError: [Errno 2] No such file or directory: '/tmp/pip-build-qTh9qM/django-easy-timezones/requirements.txt'
Complete output from command python setup.py egg_info:
Traceback (most recent call last):

File "", line 17, in

File "/tmp/pip-build-qTh9qM/django-easy-timezones/setup.py", line 12, in

with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as f:

IOError: [Errno 2] No such file or directory: '/tmp/pip-build-qTh9qM/django-easy-timezones/requirements.txt'


Cleaning up...
Command python setup.py egg_info failed with error code 1 in /tmp/pip-build-qTh9qM/django-easy-timezones
Storing debug log for failure in /root/.pip/pip.log

Geolite2

Hi
when checking the geolite website they mentioned that they now moved to the geolite2 format.
Do you have any plans to upgrade the plugin to use the new format?

Syntax error, Dj1.9 Python 3.4

Hi
I get the below error when I start my application

from .utils import get_ip_address_from_request, is_valid_ip, is_local_ip                                                           
  File "/home/cabox/Envs/myproject/lib/python3.4/site-packages/easy_timezones/utils.py", line 13                                         
    except ValueError, e:                                                                                                              
                     ^                                                                                                                 
SyntaxError: invalid syntax

AttributeError: 'AnonymousUser' object has no attribute 'timezone'

Hi Miserlou,

I'm using your package to auto detect timezone.
I have a problem with trying to save the detected timezone into my user model.
Basically I have a field 'timezone' inside my customized user model , but I cannot access it to save unless user have to logged-in first?!

The 'django-easy-timezones' provide instance but it is 'AnonymousUser' only:

detected_timezone.send(sender=get_user_model(), instance=request.user, timezone=tz)
(line 88 middleware.py)

My error was:
'AnonymousUser' object has no attribute 'timezone'

How do I modify 'django-easy-timezones' to work only for logged user only ?

I'm using default signals in my views.py:

"from easy_timezones.signals import detected_timezone

@receiver(detected_timezone, sender=MyUserModel)
def process_timezone(sender, instance, timezone, **kwargs):
if instance.timezone != timezone:
instance.timezone = timezone
instance.save()"

Online Example with detection

It would be fine if you could have an online example. Because my ip detecting as UTC, but maybe it localhost (127.0.0.1).

Invalid database type, expected City

Followed your instructions and am getting this error out of the gate:

Internal Server Error: /
Traceback (most recent call last):
  File "/Users/Craig/Sites/dfw/.dfw/lib/python2.7/site-packages/django/core/handlers/base.py", line 90, in get_response
    response = middleware_method(request)
  File "/Users/Craig/Sites/dfw/.dfw/lib/python2.7/site-packages/easy_timezones/middleware.py", line 37, in process_request
    tz = db.time_zone_by_addr(ip)
  File "/Users/Craig/Sites/dfw/.dfw/lib/python2.7/site-packages/pygeoip/__init__.py", line 628, in time_zone_by_addr
    raise GeoIPError(message)
GeoIPError: Invalid database type, expected City

At the moment of the error, my _database_type = 1 and const.CITY_EDITIONS = (6, 2, 30)

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.