Reputation: 2231
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?
Upvotes: 3
Views: 1544
Reputation: 292
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",)
Upvotes: 2
Reputation: 2541
I had the same problem and i solved it by defining the field in ModelForm:
date = forms.DateTimeField(input_formats=['%d-%m-%Y %H:%M:%S']
class Meta:
model = Quotation
fields = [
'full_name',
'organisation',
'address',
'date',
'type',
'description',
'budget',
]
def __init__(self, *args, **kwargs):
super(YourModelName, self).__init__(*args, **kwargs)
self.fields['date'].widget.attrs.update({'class': 'form-control', 'id': 'm_datetimepicker_1'})
Also modify your javascript format to 'dd-mm-yyyy hh:ii:ss'
Upvotes: 1