~ubuntu-branches/ubuntu/quantal/python-django/quantal

« back to all changes in this revision

Viewing changes to django/newforms/extras/widgets.py

  • Committer: Bazaar Package Importer
  • Author(s): Scott James Remnant, Eddy Mulyono
  • Date: 2008-09-16 12:18:47 UTC
  • mfrom: (1.1.5 upstream) (4.1.1 lenny)
  • Revision ID: james.westby@ubuntu.com-20080916121847-mg225rg5mnsdqzr0
Tags: 1.0-1ubuntu1
* Merge from Debian (LP: #264191), remaining changes:
  - Run test suite on build.

[Eddy Mulyono]
* Update patch to workaround network test case failures.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
"""
2
 
Extra HTML Widget classes
3
 
"""
4
 
 
5
 
from django.newforms.widgets import Widget, Select
6
 
from django.utils.dates import MONTHS
7
 
import datetime
8
 
 
9
 
__all__ = ('SelectDateWidget',)
10
 
 
11
 
class SelectDateWidget(Widget):
12
 
    """
13
 
    A Widget that splits date input into three <select> boxes.
14
 
 
15
 
    This also serves as an example of a Widget that has more than one HTML
16
 
    element and hence implements value_from_datadict.
17
 
    """
18
 
    month_field = '%s_month'
19
 
    day_field = '%s_day'
20
 
    year_field = '%s_year'
21
 
 
22
 
    def __init__(self, attrs=None, years=None):
23
 
        # years is an optional list/tuple of years to use in the "year" select box.
24
 
        self.attrs = attrs or {}
25
 
        if years:
26
 
            self.years = years
27
 
        else:
28
 
            this_year = datetime.date.today().year
29
 
            self.years = range(this_year, this_year+10)
30
 
 
31
 
    def render(self, name, value, attrs=None):
32
 
        try:
33
 
            value = datetime.date(*map(int, value.split('-')))
34
 
            year_val, month_val, day_val = value.year, value.month, value.day
35
 
        except (AttributeError, TypeError, ValueError):
36
 
            year_val = month_val = day_val = None
37
 
 
38
 
        output = []
39
 
 
40
 
        month_choices = MONTHS.items()
41
 
        month_choices.sort()
42
 
        select_html = Select(choices=month_choices).render(self.month_field % name, month_val)
43
 
        output.append(select_html)
44
 
 
45
 
        day_choices = [(i, i) for i in range(1, 32)]
46
 
        select_html = Select(choices=day_choices).render(self.day_field % name, day_val)
47
 
        output.append(select_html)
48
 
 
49
 
        year_choices = [(i, i) for i in self.years]
50
 
        select_html = Select(choices=year_choices).render(self.year_field % name, year_val)
51
 
        output.append(select_html)
52
 
 
53
 
        return u'\n'.join(output)
54
 
 
55
 
    def value_from_datadict(self, data, name):
56
 
        y, m, d = data.get(self.year_field % name), data.get(self.month_field % name), data.get(self.day_field % name)
57
 
        if y and m and d:
58
 
            return '%s-%s-%s' % (y, m, d)
59
 
        return None