Alan Weng
Alan Weng

Reputation: 656

Django calendar form invalid input

I currently have this class in form.py

class DateForm(forms.Form):
     date = forms.DateTimeField(
     input_formats=['%m/%d/%Y %H:%M'],
     widget=forms.DateTimeInput(attrs={
         'class': 'form-control datetimepicker-input',
         'data-target': '#datetimepicker1'
     }))

In my views.py I have this snippet of code where it checks if the form was valid

checkout = request.POST.get('place_order')
        if checkout:
            form = DateForm(request.POST)
            print(form)
            if form.is_valid():
                pickup_time = form.cleaned_data['date']

However, im getting this error

<tr><th><label for="id_date">Date:</label></th><td><ul class="errorlist"><li>Enter a valid 
date/time.</li></ul><input type="text" name="date" value="04/05/0001 6:07 PM" class="form- 
control datetimepicker-input" data-target="#datetimepicker1" required id="id_date"></td>. 
</tr>

When I submit the form on the webpage im using this format

enter image description here

Since the formats line up, I'm confused on whether it really is an error with the input method or something bigger.

Upvotes: 1

Views: 115

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

The input format is not entirely the same. Indeed, if we parse this with the datetime module, we get:

>>> from datetime import datetime
>>> datetime.strptime('04/05/0001 6:07 PM', '%m/%d/%Y %H:%M')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.6/_strptime.py", line 365, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains:  PM

So the PM part here is not parsed, you can parse that with the %p directive, so:

>>> datetime.strptime('04/05/0001 6:07 PM', '%m/%d/%Y %H:%M %p')
datetime.datetime(1, 4, 5, 6, 7)

The input_formats should thus be:

class DateForm(forms.Form):
     date = forms.DateTimeField(
     input_formats=['%m/%d/%Y %H:%M %p'],
     widget=forms.DateTimeInput(attrs={
         'class': 'form-control datetimepicker-input',
         'data-target': '#datetimepicker1'
     }))

Upvotes: 1

Related Questions