Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SplitDateTimeWidget #74

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions datetimewidget/fields.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from time import strptime, strftime, mktime
from datetime import datetime, time
from django import forms
from django.db import models
from django.conf import settings
from django.forms import fields
from django.forms.utils import from_current_timezone
from widgets import NewAdminSplitDateTimeWidget
from django.utils import timezone as tz
from django.forms.fields import TimeField
from django.core.validators import MaxValueValidator, MinValueValidator

from pytz import timezone

class NewAdminSplitDateTimeField(fields.MultiValueField):
def __init__(self, input_date_formats=None, *args, **kwargs):
errors = self.default_error_messages.copy()
if 'error_messages' in kwargs:
errors.update(kwargs['error_messages'])
localize = kwargs.get('localize', False)
all_fields = (
fields.DateField(input_formats=input_date_formats,
localize=localize),
fields.IntegerField(min_value=1, max_value=12),
fields.IntegerField(min_value=0, max_value=59),
fields.ChoiceField(choices=[('AM','AM'),('PM','PM')])
)
super(NewAdminSplitDateTimeField, self).__init__(all_fields, *args, **kwargs)

def compress(self, data_list):
if data_list:
if data_list[0] in self.empty_values:
raise ValidationError(self.error_messages['invalid_date'], code='invalid_date')
if (data_list[1] in self.empty_values or
data_list[2] in self.empty_values or
data_list[3] in self.empty_values):
raise ValidationError(self.error_messages['invalid_time'], code='invalid_time')
hour = data_list[1]
if data_list[3] == 'PM' and data_list[1] != 12:
hour += 12
if data_list[3] == 'AM' and data_list[1] == 12:
hour = 0
input_time = time(hour, data_list[2])
date_list = [data_list[0], input_time]
result = datetime.combine(*date_list)
return from_current_timezone(result)
return None

def strptime(self, value, format):
return datetime.datetime.strptime(force_str(value), format)
2 changes: 1 addition & 1 deletion datetimewidget/static/css/datetimepicker.css
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
}

.datetimepicker-inline {
width: 220px;
width: 80px;
}

.datetimepicker.datetimepicker-rtl {
Expand Down
85 changes: 84 additions & 1 deletion datetimewidget/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,19 @@
import uuid

from django.forms import forms, widgets
from django.forms.widgets import MultiWidget, DateTimeInput, DateInput, TimeInput
from django.forms.widgets import (
Select, MultiWidget, DateTimeInput, DateInput,
TimeInput)
from django.utils.translation import ugettext as _
from django.contrib.admin.widgets import AdminDateWidget
from django.utils.formats import get_format, get_language
from django.template.loader import render_to_string
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.six import string_types

from time import strftime

try:
from django.forms.widgets import to_current_timezone
except ImportError:
Expand Down Expand Up @@ -331,3 +339,78 @@ def __init__(self, attrs=None, options=None, usel10n=None, bootstrap_version=Non

super(TimeWidget, self).__init__(attrs, options, usel10n, bootstrap_version)

class SplitDateTimeWidget(MultiWidget):

def __init__(self, attrs=None, options=None, usel10n=None, bootstrap_version=None):
if options is None:
options = {}

date_options = {}
time_options = {}
# Set the default options to show only the datepicker object
date_options['startView'] = options.pop('date_startView', 2)
date_options['minView'] = options.pop('date_minView', 2)
date_options['format'] = options.pop('date_format', 'yyyy-mm-dd')

time_options['startView'] = options.pop('time_startView', 1)
time_options['minView'] = options.pop('time_minView', 0)
time_options['maxView'] = options.pop('time_maxView', 1)
time_options['format'] = options.pop('time_format', 'hh:ii')

date_copy = options.copy()
date_copy.update(date_options)
time_copy = options.copy()
time_copy.update(time_options)

widgets = (DateWidget(attrs=attrs, options=date_copy, usel10n=usel10n, bootstrap_version=bootstrap_version),
TimeWidget(attrs=attrs, options=time_copy, usel10n=usel10n, bootstrap_version=bootstrap_version))

super(SplitDateTimeWidget, self).__init__(widgets, attrs)

def decompress(self, value):
if value:
d = strftime("%Y-%m-%d", value.timetuple())
hour = strftime("%H", value.timetuple())
minute = strftime("%M", value.timetuple())
meridian = strftime("%p", value.timetuple())
return (d, hour+":"+minute, meridian)
else:
return (None, None, None)

def format_output(self, rendered_widgets):
"""
Given a list of rendered widgets (as strings), it inserts an HTML
linebreak between them.
Returns a Unicode string representing the HTML for the whole lot.
"""
return "Date: %s<br/>Time: %s" % (rendered_widgets[0], rendered_widgets[1])

class NewAdminSplitDateTimeWidget(MultiWidget):
def __init__(self, attrs=None, date_format=None, time_format=None):
number_attrs = {}
hours_attrs = {'min': '1', 'max': '12'}
min_attrs = {'min': '0', 'max': '59', 'step': 15}
if attrs:
number_attrs = dict(number_attrs, **attrs)
widgets = (AdminDateWidget,
NumberInput(attrs=dict(number_attrs,**hours_attrs)),
NumberInput(attrs=dict(number_attrs,**min_attrs)),
Select(attrs=attrs, choices=[('AM','AM'),('PM','PM')]))
super(NewAdminSplitDateTimeWidget, self).__init__(widgets, attrs)

def decompress(self, value):
if value:
value = to_current_timezone(value)
d = strftime("%Y-%m-%d", value.timetuple())
hour = strftime("%I", value.timetuple())
minute = strftime("%M", value.timetuple())
meridian = strftime("%p", value.timetuple())
return (d, hour, minute, meridian)
else:
return (None, None, None, None)

def format_output(self, rendered_widgets):
return format_html('<p class="datetime">{} {}<br />{} {} {} {}</p>',
_('Date:'), rendered_widgets[0],
_('Time:'), rendered_widgets[1],
rendered_widgets[2], rendered_widgets[3])