Created
August 1, 2013 17:55
-
-
Save jwineinger/6133661 to your computer and use it in GitHub Desktop.
A Django MultiValue form field that handles a text datetime input and a pytz timezone input from a select list. Also, widget classes and data-format attribute are intended for use with bootstrap-datetimepicker from https://github.com/tarruda/bootstrap-datetimepicker
This file contains 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 django import forms | |
from django.forms.fields import MultiValueField | |
import pytz | |
# provided by django-timezone-field==0.4 | |
from timezone_field import TimeZoneFormField | |
class DatetimeTZWidget(forms.MultiWidget): | |
""" | |
A widget that splits splits a datetime text entry and a timezone select list. | |
""" | |
def __init__(self): | |
widgets = ( | |
forms.DateTimeInput( | |
format='%m/%d/%Y %I:%M %p', | |
attrs={'class':'input-medium datepicker', "data-format": "MM/dd/yyyy HH:mm PP"} | |
), | |
forms.Select(choices=TimeZoneFormField().choices) | |
) | |
super(DatetimeTZWidget, self).__init__(widgets) | |
def decompress(self, value): | |
if value: | |
return value.rsplit(" ", 1) | |
return ["", ""] | |
def format_output(self, rendered_widgets): | |
return u'%s %s' % (rendered_widgets[0], rendered_widgets[1]) | |
class DatetimeTZField(MultiValueField): | |
widget = DatetimeTZWidget | |
def __init__(self, *args, **kwargs): | |
errors = self.default_error_messages.copy() | |
if 'error_messages' in kwargs: | |
errors.update(kwargs['error_messages']) | |
fields = ( | |
forms.DateTimeField(input_formats=['%m/%d/%Y %I:%M %p']), | |
TimeZoneFormField(), | |
) | |
super(DatetimeTZField, self).__init__(fields, *args, **kwargs) | |
def compress(self, data_list): | |
if data_list: | |
# first make the datetime they entered tz aware | |
_date = data_list[1].localize(data_list[0]) | |
# then convert to UTC for storage | |
return _date.astimezone(pytz.timezone('UTC')) | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment