While working on my website projects today I had the idea to use HTML/JS instead of a IP database to localize the dates and times shown on the websites.
Here are the snippets to use the JS snippets as filters for Django running on Google App Engine. You can use those filters on datetime objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | # ./utils/localdatetimefilters.py
from time import mktime
from google.appengine.ext import webapp
def localdate(value, arg=None):
from django.conf import settings
from django.template import defaultfilters
if not value:
return ''
if arg is None:
arg = settings.DATE_FORMAT
content = '''<script type="text/javascript">document.write(new Date(%d).toLocaleDateString().replace(/\s[A-Z]{3}\+[0-9]{4}/, '').replace(/\s\([\s\w]+\)/, ''));</script><noscript>%s</noscript>''' % (
mktime(value.utctimetuple())*1000,
defaultfilters.date(value, arg)
)
return content
def localtime(value, arg=None):
from django.conf import settings
from django.template import defaultfilters
if not value:
return ''
if arg is None:
arg = settings.TIME_FORMAT
content = '''<script type="text/javascript">document.write(new Date(%d).toLocaleTimeString().replace(/\s[A-Z]{3}\+[0-9]{4}/, '').replace(/\s\([\s\w]+\)/, ''));</script><noscript>%s</noscript>''' % (
mktime(value.utctimetuple())*1000,
defaultfilters.time(value, arg)
)
return content
def localdatetime(value, arg1=None, arg2=None):
from django.conf import settings
from django.template import defaultfilters
if not value:
return ''
if arg1 is None:
arg1 = settings.DATE_FORMAT
if arg2 is None:
arg2 = settings.TIME_FORMAT
content = '''<script type="text/javascript">document.write(new Date(%d).toLocaleString().replace(/\s[A-Z]{3}\+[0-9]{4}/, '').replace(/\s\([\s\w]+\)/, ''));</script><noscript>%s %s</noscript>''' % (
mktime(value.utctimetuple())*1000,
defaultfilters.date(value, arg1),
defaultfilters.time(value, arg2)
)
return content
register = webapp.template.create_template_register()
register.filter(localdate)
register.filter(localtime)
register.filter(localdatetime)
# ./main.py (Request handler)
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
def main():
webapp.template.register_template_library('utils.localdatetimefilters')
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
So many equal rows in code! What about DRY principle?
#
Please login first before commenting.