import datetime
import time
import re
from django.forms.widgets import Widget
from django.forms.util import flatatt
from django.utils.html import escape
from django.utils.encoding import smart_unicode
RE_DATE = re.compile(r'\d{4}-\d\d?-\d\d?$')
def daterange(start_date, end_date):
start_date = datetime.datetime.strptime(start_date, '%Y-%M-%d')
end_date = datetime.datetime.strptime(end_date, '%Y-%M-%d')
for n in range((end_date - start_date).days+1):
yield start_date + datetime.timedelta(n)
class SelectDateWidget(Widget):
field = '%s_date'
def __init__(self, start_date, end_date, attrs=None, required=True):
self.attrs = attrs or {}
self.required = required
self.start_date = start_date
self.end_date = end_date
def render(self, name, value, attrs=None, choices=()):
if value is None: value = ''
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<select%s>' % flatatt(final_attrs)]
str_value = smart_unicode(value)
for single_date in daterange(self.start_date, self.end_date):
output.append(u'<option value="%s">%s</option>' % (time.strftime("%Y-%m-%d", single_date.timetuple()), time.strftime("%a %B %d, %Y", single_date.timetuple())))
output.append(u'</select>')
return u'\n'.join(output)
Comments
Creating new widget is useless. You can use base
Selectwidget.#
Without the intention of taking out credit from the author silent1mezzo, it's incredible the alternative of cricogik provided in just a few lines of code. Conclussion: python is awesome. Regards!
#