Search code examples
djangodjango-formsbootstrap-datetimepicker

Django: Form widget not accepting date format provided by bootstrapdatetimepicker


I have the following problem: I have a django form that uses the 'bootstrapdatetimepicker' widget for a datetimefield. However, when I try to post the form it throws a 'format is invalid' error.

I am using a local (Dutch) timeformat, but I have included this new format in both the forms.py code (see below)

    class Meta:
    model = Quotation
    fields = [
        'full_name',
        'organisation',
        'address',            
        'date',
        'type',            
        'description',
        'budget',
    ]

    widgets = {'date': DateTimeInput(
        attrs={'id': 'datetimepicker1'},
        format='%d-%m-%Y %H:%M:%S')}

and in the template as well,

    <div class="col-md-12 speaker-form" id="offerte">            
        {% csrf_token %}
        {% crispy form %}
    </div>


<script>

        $(function () {

            $('#datetimepicker1').datetimepicker({
                format:'DD-MM-YYYY HH:mm:ss',
                defaultDate: new Date(),
                icons: {
                    up: "fa fa-chevron-circle-up",
                    down: "fa fa-chevron-circle-down",
                    next: 'fa fa-chevron-circle-right',
                    previous: 'fa fa-chevron-circle-left',                        
                }
            });
        });

    </script>

Does anyone know what I am doing wrong? Why are my 'format' overrides in both the Python and Javascript code not working as they should?


Solution

  • It appears that the JS library and DateTimeInputField are correctly configured to allow the new datetime format, but the model cannot validate the new datetime format. Accordingly it will not save the data.

    If this is correct, settings.py can be modified to allow for different input formats. Be sure that USE_L10N = False otherwise it will override the custom formats listed below.

    Add the following to the bottom of settings.py:

    from django.conf.global_settings import DATETIME_INPUT_FORMATS, DATE_INPUT_FORMATS
    DATE_INPUT_FORMATS += ("%d-%m-%Y",)
    DATETIME_INPUT_FORMATS += ("%d-%m-%Y %H:%M:%S",)