In the html it displays a form, if I don't select any date from the datetime picker, the form could be submitted successfully.
But once I selected a date then I couldn't submit it. So I guess there might be something wrong in the date time format.
The Datetime picker works in the html, it shows dropdown list and I could also select it. Just I couldn't submit the form if I select a date.
form html snippet for date time picker
$(function() {
$('.date-picker').datepicker(
{
dateFormat: "yymm",
changeMonth: true,
changeYear: true,
showButtonPanel: true,
onClose: function(dateText, inst) {
function isDonePressed(){
return ($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1);
}
if (isDonePressed()){
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1)).trigger('change');
$('.date-picker').focusout()//Added to remove focus from datepicker input box on selecting date
}
},
beforeShow : function(input, inst) {
inst.dpDiv.addClass('month_year_datepicker')
if ((datestr = $(this).val()).length > 0) {
year = datestr.substring(datestr.length-4, datestr.length);
month = datestr.substring(0, 2);
$(this).datepicker('option', 'defaultDate', new Date(year, month-1, 1));
$(this).datepicker('setDate', new Date(year, month-1, 1));
$(".ui-datepicker-calendar").hide();
}
}
})
});
models.py
start_date=models.DateField(auto_now=False, auto_now_add=False)
end_date=models.DateField(auto_now=False, auto_now_add=False)
forms.py
widgets = {
'start_date': forms.DateInput(attrs={'class':'datepicker'}),
'end_date': forms.DateInput(attrs={'class':'datepicker'}),
}
In the html, the date format is like 201010 (YYYYMM).
I was wondering if it was because the date format in html is not the same as in models, that's why I couldn't submit it.
Then please tell me how could I correct my models or forms if in this situation? The date format should be like in html (YYYYMM) 201003, etc.
You need to configure the form fields in your form class to accept your chosen date format:
start_date = forms.DateField(widget=DateInput(format='%Y%m'), input_formats=['%Y%m'])
end_date = forms.DateField(widget=DateInput(format='%Y%m'), input_formats=['%Y%m'])
(This should work in both a regular Form
and a ModelForm
).