Search code examples
pythondjangodjango-generic-views

How to change the time format in django in a generic class based view


Is there a way to change the format for datetime fields when using CreateView or UpdateView? I am trying to get the form to accept dates in the form of something like "2016-12-29 03:49 PM". I know the format should be '%Y-%m-%d %I:%M %p', and this tests just fine in the shell. I just don't know how to get it working using CreateView or UpdateView, but it seems that it should be able to be done.


Solution

  • You need to update your Form Class to accept other input formats. Your form should look something like this:

    class YourForm(ModelForm):
        date_of_birth = DateTimeField(input_formats='%Y-%m-%d %I:%M %p')
        class Meta:
            model = YourModel
    

    However, it's probably better to put all of your acceptable input formats in a variable and call it from your settings.py like this:

    settings.py
    DATE_INPUT_FORMATS = [
        '%Y-%m-%d %H:%M:%S',
        '%m/%d/%Y %H:%M:%S',
        '%Y-%m-%d %I:%M %p',
    ]
    
    forms.py
    class YourForm(ModelForm):
        date_of_birth = DateTimeField(input_formats=settings.DATE_INPUT_FORMATS)
        class Meta:
            model = YourClass
    

    Lastly, I wouldn't leave it up to the user to type a date in manually anyways (assuming this view is for humans), give them a DateTime widget to select it for them. You can find info about the widgets here: https://docs.djangoproject.com/en/1.10/ref/forms/widgets/

    and info about the datetime Form Field here: https://docs.djangoproject.com/en/1.10/ref/forms/fields/#datetimefield