Ticket #5526: localflavor_datetimefields.patch

File localflavor_datetimefields.patch, 12.6 KB (added by Jan Rademaker, 17 years ago)

Reattached the patch

  • django/contrib/localflavor/nl/__init__.py

     
     1LOCALES = (
     2    'nl_NL',
     3    'nl_NL.UTF-8', 'nl_NL.ISO8859-1',  # Some OSes need these (e.g., FreeBSD)
     4)
  • django/contrib/localflavor/nl/forms.py

     
    88from django.newforms.fields import Field, Select, EMPTY_VALUES
    99from django.utils.translation import ugettext as _
    1010from django.utils.encoding import smart_unicode
     11from django.contrib.localflavor.generic import forms
     12from django.contrib.localflavor.nl.widgets import DateTimeInput
     13from django.contrib.localflavor.nl import LOCALES
    1114
     15DATE_INPUT_FORMATS = (
     16    '%d-%m-%Y', '%d/%m/%Y', # '25-10-2006', '25/10/2006'
     17    '%d/%m/%y',             # '25/10/06'
     18    '%d %b %Y', '%d %B %Y', # '25 okt 2006', '25 oktober 2006'
     19)
     20
     21DATETIME_INPUT_FORMATS = (
     22    '%d-%m-%Y %H:%M:%S',    # '25-10-2006 14:30:59'
     23    '%d-%m-%Y %H:%M',       # '25-10-2006 14:30'
     24    '%d-%m-%Y',             # '25-10-2006'
     25    '%d/%m/%Y %H:%M:%S',    # '25/10/2006 14:30:59'
     26    '%d/%m/%Y %H:%M',       # '25/10/2006 14:30'
     27    '%d/%m/%Y',             # '25/10/2006'
     28    '%d-%m-%y %H:%M:%S',    # '25-10-06 14:30:59'
     29    '%d-%m-%y %H:%M',       # '25-10-06 14:30'
     30    '%d-%m-%y',             # '25-10-06'
     31    '%d/%m/%y %H:%M:%S',    # '25/10/06 14:30:59'
     32    '%d/%m/%y %H:%M',       # '25/10/06 14:30'
     33    '%d/%m/%y',             # '25/10/06'
     34)
     35
     36DATE_OUTPUT_FORMAT = '%d-%m-%Y'
     37DATETIME_OUTPUT_FORMAT = '%d-%m-%Y %H:%M:%S'
     38
    1239pc_re = re.compile('^\d{4}[A-Z]{2}$')
    1340sofi_re = re.compile('^\d{9}$')
    1441numeric_re = re.compile('^\d+$')
     
    90117            raise ValidationError(msg)
    91118       
    92119        return value
     120
     121class DateField(forms.DateField):
     122    """
     123    A DateField using a Dutch locale.
     124    """
     125    widget = DateTimeInput(DATE_OUTPUT_FORMAT)
     126    locales = LOCALES
     127    def __init__(self, input_formats=DATE_INPUT_FORMATS, *args, **kwargs):
     128        super(DateField, self).__init__(input_formats=input_formats, *args, **kwargs)
     129
     130class DateTimeField(forms.DateTimeField):
     131    """
     132    A DateTimeField using a Dutch locale.
     133    """
     134    widget = DateTimeInput(DATETIME_OUTPUT_FORMAT)
     135    locales = LOCALES
     136    def __init__(self, input_formats=DATETIME_INPUT_FORMATS, *args, **kwargs):
     137        super(DateTimeField, self).__init__(input_formats=input_formats, *args, **kwargs)
  • django/contrib/localflavor/nl/widgets.py

     
     1from django.contrib.localflavor.generic import widgets
     2from django.contrib.localflavor.nl import LOCALES
     3
     4class DateTimeInput(widgets.DateTimeInput):
     5    locales = LOCALES
  • django/contrib/localflavor/generic/forms.py

     
     1import locale
     2
    13from django import newforms as forms
    24
    35DEFAULT_DATE_INPUT_FORMATS = (
     
    2022    '%d/%m/%y',              # '25/10/06'
    2123)
    2224
    23 class DateField(forms.DateField):
     25def try_locales(locales):
    2426    """
     27    Try to set the locale to one of the specified locales.  Stop as soon as
     28    one of the locales is available.
     29    """
     30    for _locale in locales:
     31        try:
     32            locale.setlocale(locale.LC_TIME, _locale)
     33            break
     34        except locale.Error:
     35            pass
     36
     37class LocalizedDateTimeField(object):
     38    locales = ()
     39
     40    def clean(self, value):
     41        """
     42        Temporarily replace the current locale with the locale necessary to
     43        properly validate given value.
     44        """
     45        cur_locale = locale.setlocale(locale.LC_TIME)
     46        try:
     47            try_locales(self.locales)
     48            return super(LocalizedDateTimeField, self).clean(value)
     49        finally:
     50            locale.setlocale(locale.LC_TIME, cur_locale)
     51
     52class DateField(LocalizedDateTimeField, forms.DateField):
     53    """
    2554    A date input field which uses non-US date input formats by default.
    2655    """
    2756    def __init__(self, input_formats=None, *args, **kwargs):
    2857        input_formats = input_formats or DEFAULT_DATE_INPUT_FORMATS
    2958        super(DateField, self).__init__(input_formats=input_formats, *args, **kwargs)
    3059
    31 class DateTimeField(forms.DateTimeField):
     60class DateTimeField(LocalizedDateTimeField, forms.DateTimeField):
    3261    """
    3362    A date and time input field which uses non-US date and time input formats
    3463    by default.
  • django/contrib/localflavor/generic/widgets.py

     
     1import locale
     2
     3from django.newforms.widgets import TextInput
     4from django.contrib.localflavor.generic.forms import try_locales
     5
     6class DateTimeInput(TextInput):
     7    locales = []
     8    def __init__(self, date_output_format, locales=None, *args, **kwargs):
     9        super(DateTimeInput, self).__init__(*args, **kwargs)
     10        self.date_output_format = date_output_format
     11        self.locales = locales or self.locales
     12   
     13    def render(self, name, value, attrs=None):
     14        if hasattr(value, 'strftime'):
     15            try:
     16                cur_locale = locale.setlocale(locale.LC_TIME)
     17                try_locales(self.locales)
     18                str_value = value.strftime(self.date_output_format)
     19                return super(DateTimeInput, self).render(name, str_value, attrs)
     20            finally:
     21                locale.setlocale(locale.LC_TIME, cur_locale)
     22        else:
     23            return super(DateTimeInput, self).render(name, value, attrs)
  • tests/regressiontests/forms/localflavor.py

     
    15291529>>> s.render('provinces', 'OV')
    15301530u'<select name="provinces">\n<option value="DR">Drente</option>\n<option value="FL">Flevoland</option>\n<option value="FR">Friesland</option>\n<option value="GL">Gelderland</option>\n<option value="GR">Groningen</option>\n<option value="LB">Limburg</option>\n<option value="NB">Noord-Brabant</option>\n<option value="NH">Noord-Holland</option>\n<option value="OV" selected="selected">Overijssel</option>\n<option value="UT">Utrecht</option>\n<option value="ZE">Zeeland</option>\n<option value="ZH">Zuid-Holland</option>\n</select>'
    15311531
     1532# Dutch DateField ###########################################################
     1533
     1534>>> import datetime
     1535>>> from django.contrib.localflavor.nl.forms import DateField
     1536>>> f = DateField()
     1537>>> f.clean(datetime.date(2006, 10, 25))
     1538datetime.date(2006, 10, 25)
     1539>>> f.clean('25-10-2006')
     1540datetime.date(2006, 10, 25)
     1541>>> f.clean('25/10/2006')
     1542datetime.date(2006, 10, 25)
     1543>>> f.clean('25/10/06')
     1544datetime.date(2006, 10, 25)
     1545>>> f.clean('25 okt 2006')
     1546datetime.date(2006, 10, 25)
     1547>>> f.clean('25 oktober 2006')
     1548datetime.date(2006, 10, 25)
     1549>>> f.clean('2006-10-25')
     1550Traceback (most recent call last):
     1551    ...
     1552ValidationError: [u'Enter a valid date.']
     1553>>> f.clean('October 25 2006')
     1554Traceback (most recent call last):
     1555    ...
     1556ValidationError: [u'Enter a valid date.']
     1557
     1558DateField accepts an optional input_formats parameter:
     1559>>> f = DateField(input_formats=['%Y %B %d'])
     1560>>> f.clean(datetime.date(2006, 10, 25))
     1561datetime.date(2006, 10, 25)
     1562>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30))
     1563datetime.date(2006, 10, 25)
     1564>>> f.clean('2006 oktober 1')
     1565datetime.date(2006, 10, 1)
     1566
     1567The input_formats parameter overrides all default input formats,
     1568so the default formats won't work unless you specify them:
     1569>>> f.clean('25-10-2006')
     1570Traceback (most recent call last):
     1571...
     1572ValidationError: [u'Enter a valid date.']
     1573>>> f.clean('25/10/2006')
     1574Traceback (most recent call last):
     1575...
     1576ValidationError: [u'Enter a valid date.']
     1577>>> f.clean('25/10/06')
     1578Traceback (most recent call last):
     1579...
     1580ValidationError: [u'Enter a valid date.']
     1581
     1582# Dutch DateTimeField #######################################################
     1583
     1584>>> import datetime
     1585>>> from django.contrib.localflavor.nl.forms import DateTimeField
     1586>>> f = DateTimeField()
     1587>>> f.clean(datetime.date(2006, 10, 25))
     1588datetime.datetime(2006, 10, 25, 0, 0)
     1589>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30))
     1590datetime.datetime(2006, 10, 25, 14, 30)
     1591>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))
     1592datetime.datetime(2006, 10, 25, 14, 30, 59)
     1593>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))
     1594datetime.datetime(2006, 10, 25, 14, 30, 59, 200)
     1595>>> f.clean('25-10-2006 14:30:45')
     1596datetime.datetime(2006, 10, 25, 14, 30, 45)
     1597>>> f.clean('25-10-2006 14:30:00')
     1598datetime.datetime(2006, 10, 25, 14, 30)
     1599>>> f.clean('25-10-2006 14:30')
     1600datetime.datetime(2006, 10, 25, 14, 30)
     1601>>> f.clean('25-10-2006')
     1602datetime.datetime(2006, 10, 25, 0, 0)
     1603>>> f.clean('25/10/2006 14:30:45')
     1604datetime.datetime(2006, 10, 25, 14, 30, 45)
     1605>>> f.clean('25/10/2006 14:30:00')
     1606datetime.datetime(2006, 10, 25, 14, 30)
     1607>>> f.clean('25/10/2006 14:30')
     1608datetime.datetime(2006, 10, 25, 14, 30)
     1609>>> f.clean('25/10/2006')
     1610datetime.datetime(2006, 10, 25, 0, 0)
     1611>>> f.clean('25/10/06 14:30:45')
     1612datetime.datetime(2006, 10, 25, 14, 30, 45)
     1613>>> f.clean('25/10/06 14:30:00')
     1614datetime.datetime(2006, 10, 25, 14, 30)
     1615>>> f.clean('25/10/06 14:30')
     1616datetime.datetime(2006, 10, 25, 14, 30)
     1617>>> f.clean('25/10/06')
     1618datetime.datetime(2006, 10, 25, 0, 0)
     1619>>> f.clean('hello')
     1620Traceback (most recent call last):
     1621...
     1622ValidationError: [u'Enter a valid date/time.']
     1623>>> f = DateTimeField(input_formats=['%Y %m %d %H:%M'])
     1624>>> f.clean(datetime.date(2006, 10, 25))
     1625datetime.datetime(2006, 10, 25, 0, 0)
     1626>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30))
     1627datetime.datetime(2006, 10, 25, 14, 30)
     1628>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))
     1629datetime.datetime(2006, 10, 25, 14, 30, 59)
     1630>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))
     1631datetime.datetime(2006, 10, 25, 14, 30, 59, 200)
     1632>>> f.clean('2006 10 25 14:30')
     1633datetime.datetime(2006, 10, 25, 14, 30)
     1634
     1635The input_formats parameter overrides all default input formats,
     1636so the default formats won't work unless you specify them:
     1637>>> f.clean('25-10-2006 14:30:45')
     1638Traceback (most recent call last):
     1639...
     1640ValidationError: [u'Enter a valid date/time.']
     1641
     1642>>> f = DateTimeField(required=False)
     1643>>> f.clean(None)
     1644>>> repr(f.clean(None))
     1645'None'
     1646>>> f.clean('')
     1647>>> repr(f.clean(''))
     1648'None'
     1649
     1650# A form using DateTimeInput with a Dutch locale ############################
     1651
     1652>>> import django.newforms as forms
     1653>>> from django.contrib.localflavor.nl.widgets import DateTimeInput
     1654>>> class NLDateTimeForm(forms.Form):
     1655...     date = DateField()
     1656...     date_custom_format = DateField(widget=DateTimeInput('%d %B %Y'))
     1657...     datetime = DateTimeField()
     1658...     foo = DateField()
     1659>>> f = NLDateTimeForm(initial={
     1660...     'date': datetime.date(2006, 10, 25),
     1661...     'date_custom_format': datetime.date(2006, 10, 25),
     1662...     'datetime': datetime.datetime(2006, 10, 25, 10, 11, 12),
     1663...     'foo': 'bar',
     1664... })
     1665>>> print f['date']
     1666<input type="text" name="date" value="25-10-2006" id="id_date" />
     1667>>> print f['date_custom_format']
     1668<input type="text" name="date_custom_format" value="25 oktober 2006" id="id_date_custom_format" />
     1669>>> print f['datetime']
     1670<input type="text" name="datetime" value="25-10-2006 10:11:12" id="id_datetime" />
     1671>>> print f['foo']
     1672<input type="text" name="foo" value="bar" id="id_foo" />
     1673
    15321674# ARProvinceField #############################################################
    15331675
    15341676>>> from django.contrib.localflavor.ar.forms import ARProvinceSelect
     
    21942336>>> repr(f.clean(''))
    21952337'None'
    21962338
     2339# LocalizedDateTimeField #####################################################
     2340>>> # Make sure the locale is reset after use.
     2341>>> import locale
     2342>>> from django.contrib.localflavor.nl.forms import DateField
     2343>>> locale_before = locale.setlocale(locale.LC_TIME)
     2344>>> f = DateField()
     2345>>> try:
     2346...     f.clean('foo')
     2347... except:
     2348...     pass
     2349>>> locale_after = locale.setlocale(locale.LC_TIME)
     2350>>> locale_before == locale_after
     2351True
     2352
    21972353"""
Back to Top