我使用 jQuery 月份选择器(没有日期),格式如下:201110。
我想设置一个最小日期(参见代码),所以首先在 django forms.py 中定义它的最小日期,然后将此日期解析为 html。首先有一个最小/最大范围。 (虽然现在这不起作用)。
然后,为了实现“to”日期始终晚于“from”日期,我还需要使用 min/max 函数,然后它会覆盖我从 SQL 设置的前一个月范围。
目前的情况是我可以实现“到”日期>“从”日期。但最小日期(来自 MYSQL)现在不起作用。
我该如何解决这个冲突,请告诉我。提前致谢
感谢您提前回复。
<script type="text/javascript">
$(function() {
$( "#from, #to" ).datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'yy MM',
minDate: $(this).date-min, ///it is here doesn't work, the minDate is coming from Django
onClose: function(dateText, inst) {
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));
},
beforeShow : function(input, inst) {
if ((datestr = $(this).val()).length > 0) {
year = datestr.substring(datestr.length-4, datestr.length);
month = jQuery.inArray(datestr.substring(0, datestr.length-5), $(this).datepicker('option', 'monthNames'));
$(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
$(this).datepicker('setDate', new Date(year, month, 1));
}
var other = this.id == "from" ? "#to" : "#from";
var option = this.id == "from" ? "maxDate" : "minDate";
if ((selectedDate = $(other).val()).length > 0) {
year = selectedDate.substring(selectedDate.length-4, selectedDate.length);
month = jQuery.inArray(selectedDate.substring(0, selectedDate.length-5), $(this).datepicker('option', 'monthNames'));
$(this).datepicker( "option", option, new Date(year, month, 1));
}
}
});
$("#btnShow").click(function(){
if ($("#from").val().length == 0 || $("#to").val().length == 0){
alert('All fields are required');
}
else{
alert('Selected Month Range :'+ $("#from").val() + ' to ' + $("#to").val());
}
})
});
</script>
我如何在 dJango 中定义我的最小日期:
在 models.py 中
class XXX(models.Model):
start_date=models.DateField(auto_now_add=True)
end_date=models.DateField(auto_now_add=True)
在forms.py中
class Meta:
model = XXX
fields = ('start_date','end_date')
date_min=XXX.objects.all().aggregate(Min('date')) <this field is NOT defined in models.py, is that OK?; and format is like 2011-11-01 -->
widgets = {
'start_date': forms.DateInput(attrs={'class':'datepicker',
'date-min':date_min,
}),
}