- Author:
- silent1mezzo
- Posted:
- December 15, 2010
- Language:
- Python
- Version:
- 1.2
- Score:
- -1 (after 3 ratings)
This widget will produce a select box with the range of dates that you input.
Usage:
widget=SelectDateWidget('2010-12-15', '2010-12-20')
Output:
`<select>
<option value="2010-12-15">Wed January 01, 2010</option>
<option value="2010-12-16">Thu January 02, 2010</option>
<option value="2010-12-17">Fri January 03, 2010</option>
<option value="2010-12-18">Sat January 04, 2010</option>
<option value="2010-12-19">Sun January 05, 2010</option>
<option value="2010-12-20">Mon January 06, 2010</option>
</select>`
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 | 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)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Creating new widget is useless. You can use base
Select
widget.#
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!
#
Please login first before commenting.