Search code examples
pythondjangovalidationmodeldjango-admin

Django Model DateField to_python


I am working on Django 1.4, and I have a the following doubt. When parsing between dates on Django Admin, the format should be on the format "%Y-%m-%d". I just checked the code, and the django model DateField isn't using the settings to check the valid date for "to_python".

For exmaple, the only valid format right now is:

&fecha_inicio__lte=2012-06-10

But I also want that:

&fecha_inicio__lte=06/10/2012

Solution

  • You could use this function to convert dates:

    import re
    
    def parse_slash_date(value):
        m = re.match(r'^(?P<day>[0-9]{1,2})/(?P<month>[0-9]{1,2})/(?P<year>[0-9]{4})$', value)
        if m:
            return '%s-%s-%s' % (
                m.group('year'), m.group('month'), m.group('day'))
    

    Example:

    In [4]: parse_slash_date('06/10/2012')
    Out[4]: '2012-10-06'
    

    You could also create a DateField that uses the parser:

    class YourDateField(models.DateField):
        def get_prep_lookup(self, lookup_type, value):
            if value and '/' in value:
                value = parse_slash_date(value)
            return super(YourDateField, self).get_prep_lookup(
                lookup_type, value)
    

    However, I was pretty sure that DateField was able to parse dates with slashes already... But I just read the code of django.utils.dateparse.parse_date and it doesn't.