#34004: Bug: DateTimeField for Forms does not always respect input_formats
------------------------------------------+------------------------
               Reporter:  Emily Hontoria  |          Owner:  nobody
                   Type:  Bug             |         Status:  new
              Component:  Forms           |        Version:  3.1
               Severity:  Normal          |       Keywords:
           Triage Stage:  Unreviewed      |      Has patch:  0
    Needs documentation:  0               |    Needs tests:  0
Patch needs improvement:  0               |  Easy pickings:  0
                  UI/UX:  0               |
------------------------------------------+------------------------
 When creating a new form with a single `DateTimeField` and supplying a
 string formatted datetime (for example `"2021-12-10 10:00:00"`) the form
 is considered valid even if the given datetime is not in a supported
 `input_formats`.

 Relevant doc:
 https://docs.djangoproject.com/en/3.2/ref/forms/fields/#datetimefield

 Small reproducible snippet:
 {{{
         test_sets = [
             # Missing seconds
             {"input_format": "%Y-%m-%d %H:%M:%S", "dt": "2018-12-10
 21:00"},
             # Hour in 24 format instead of 12
             {"input_format": "%Y-%m-%d %I:%M", "dt": "2018-12-10 21:00"}
         ]

         for incorrect_pair in test_sets:
             dt_val = incorrect_pair["dt"]
             input_format_val = incorrect_pair["input_format"]

             class DateTimeFormTester(forms.Form):
                 dt =
 forms.DateTimeField(input_formats=[incorrect_pair["input_format"]])

             test_form = DateTimeFormTester({"dt": incorrect_pair["dt"]})
             if test_form.is_valid():
                 print(f"Incorrectly determined {dt_val} as valid for
 input_format {input_format_val}")
 }}}

 Was not a problem in Django 3.0.14, can reproduce in Django 3.1.14 with
 the above snippet.

 I believe the problem stems from this bit of code in django.forms.fields:
 {{{
         try:
             result = parse_datetime(value.strip())
         except ValueError:
             raise ValidationError(self.error_messages['invalid'],
 code='invalid')
         if not result:
             result = super().to_python(value)
 }}}

 which means that if we are able to `parse_datetime` we never run
 `super().to_python(value)` which is what checks the format is correct.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/34004>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/010701832917e2c1-d97ec3af-1762-4a2b-a46e-7883331ef70c-000000%40eu-central-1.amazonses.com.

Reply via email to