Home > Blockchain >  Enter a valid date/time - Django Datetime Picker
Enter a valid date/time - Django Datetime Picker

Time:12-02

I'm creating a CRUD application in Django, and one of the fields in the data requires the user to enter a datetime input. This was working smoothly until this evening when I started to work on it again, however I'm getting the below error when I try to add any data the the model.

  • start_datetime
  • Enter a valid date/time.
  • [01/Dec/2022 00:34:39] "POST /activities/new/ HTTP/1.1" 200 2253

    I've tried quite a few ways to resolve this but nothing seems to be working; below if the code I have to create the activity

    class ActivityForm(forms.ModelForm):
        class Meta:
            model = Activity
            fields = ('name', 'start_datetime', 'end_time',
                      'location', 'town', 'description')
            labels = {
                'name': 'Activity Type',
                'start_datetime': 'Date & Time of Activity',
                'end_time': 'End Time',
                'location': 'County',
                'town': 'Town (optional)',
                'description': 'Description',
            }
            widgets = {
                'start_datetime': DateTimePickerInput(),
                'end_time': TimePickerInput(),
    
            }
    
    class DateTimePickerInput(forms.DateTimeInput):
        input_type = 'datetime-local'
    

    This is the model field for the start_datetime:

    start_datetime = models.DateTimeField()

    Does anyone have any ideas on how to resolve this?

    Thanks!

    CodePudding user response:

    Works smoothly in my test:

    forms.py

    class ActivityForm(forms.ModelForm):
        class Meta:
            model = models.Activity
            fields = ('name', 'start_datetime', 'end_time',
                      'location', 'town', 'description')
            labels = {
                'name': 'Activity Type',
                'start_datetime': 'Date & Time of Activity',
                'end_time': 'End Time',
                'location': 'County',
                'town': 'Town (optional)',
                'description': 'Description',
            }
            widgets = {
                'start_datetime': DateTimeInput(attrs={'type': 'datetime-local'}),
                'end_time': TimeInput(attrs={'type': 'time'}),
            }
    

    Django expects the following datetime-input-formats:

    [
        '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
        '%Y-%m-%d %H:%M:%S.%f',  # '2006-10-25 14:30:59.000200'
        '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
        '%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
        '%m/%d/%Y %H:%M:%S.%f',  # '10/25/2006 14:30:59.000200'
        '%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
        '%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
        '%m/%d/%y %H:%M:%S.%f',  # '10/25/06 14:30:59.000200'
        '%m/%d/%y %H:%M',        # '10/25/06 14:30'
    ]
    
    • Related