List Info

Thread: date format other than YYYY-MM-DD




date format other than YYYY-MM-DD
user name
2006-09-29 13:41:04
viestards wrote:
> thanks, suppose I have to do it this way. I just hoped
to have a
> sollution that works in admin pages too.

I also ran into this problem so I did it that hard way: I
created a
custom model DateField and a custom form DateField. (I call
them
RelaxedModelDateField and RelaxedFormDateField meaning they
are relaxed
about what format you put the date in). Every time I look at
this code
I think "this is way too complicated to simply allow
different date
formats on input/output" which is probably one of the
reasons the
forms/manipulators/validators are all getting revisited
right now.

To use this, just use RelaxedModelDateField in place of
models.DateField in your model. This works in the admin.

class RelaxedModelDateField(models.DateField):
    """A DateField that supports various date
formats
    rather than just yyyy-mm-dd. The following formats
    are allowed:
      m/-d/-yyyy    6-23-2006
      m/-d/-yy      6/23/06
      m/-d          6/23
      yyyy-mm-dd    2006-6-23
      yyyymmdd      20060623

    In the UI, the date will be displayed as
mm/dd/yyyy"""
    def __init__(self, verbose_name=None, name=None,
                 auto_now=False, auto_now_add=False,
**kwargs):
        models.DateField.__init__(self, verbose_name, name,
                                  auto_now, auto_now_add,
**kwargs)

    def get_internal_type(self):
        return "DateField"

    def to_python(self, value):
        if isinstance(value, datetime.datetime):
            return value.date()
        if isinstance(value, datetime.date):
            return value
        try:
            return toDateRelaxed(value)
        except ValueError:
            raise validators.ValidationError, gettext('Enter
a valid
date.')

    def get_manipulator_field_objs(self):
        return [RelaxedFormDateField]

    def flatten_data(self, follow, obj = None):
        val = self._get_val_from_obj(obj)
        return {self.attname:
                (val is not None and
val.strftime("%m/%d/%Y") or '')}

class RelaxedFormDateField(forms.DateField):
    """A version of forms.DateField that
automatically
    supports various formats of dates."""
    def __init__(self, field_name, is_required=False,
validator_list=None):
        forms.DateField.__init__(self, field_name,
is_required,
validator_list)

    def isValidDate(self, field_data, all_data):
        try:
            toDateRelaxed(field_data)
        except ValueError:
            raise validators.CriticalValidationError, 'Enter
a valid
date.'

    def html2python(data):
        "Converts the field into a datetime.date
object"
        try:
            return toDateRelaxed(data)
        except ValueError:
            return None
    html2python = staticmethod(html2python)


And here is the routine that actually does the
"relaxed" parsing:

# handle many formats:
# m/-d/-yyyy    6-23-2006
# m/-d/-yy      6/23/06
# m/-d          6/23
# yyyy-mm-dd    2006-6-23
# yyyymmdd      20060623
def toDateRelaxed(s):
    exps =
(r'^(?P<m>d{1,2})[/-](?P<d>d{1,2})[/-](?P<y
>d)$',
           
r'^(?P<m>d{1,2})[/-](?P<d>d{1,2})[/-](?P<y&
gt;d)$',
           
r'^(?P<m>d{1,2})[/-](?P<d>d{1,2})$',
           
r'^(?P<y>d)-(?P<m>d{1,2})-(?P<d>d{1,
2})$',
           
r'^(?P<y>d)(?P<m>d)(?P<d>d)$')
    for exp in exps:
        m = re.match(exp, s)
        if m:
            mm = int(m.group('m'))
            dd = int(m.group('d'))
            try:
                yy = int(m.group('y'))
                if yy < 100:
                    yy += 2000
            except IndexError:
                yy = datetime.date.today().year
            return datetime.date(yy, mm, dd)
    raise ValueError, s

Hope this helps...
-Dave


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the
Google Groups "Django users" group.
To post to this group, send email to django-usersgooglegroups.com
To unsubscribe from this group, send email to
django-users-unsubscribegooglegroups.com
For more options, visit this group at http://gr
oups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---

[1]

about | contact  Other archives ( Real Estate discussion Medical topics )