如何通过ajax请求django将输入的日期值从模板发送到后端



我必须根据两个日期进行查询,如果日期存在,如果不只是在没有任何过滤的情况下运行查询,但我不知道如何将日期输入值从客户端发送到服务器端,这是我的视图

def priceByDateTime(request):
start = request.GET.get('from')
end = request.GET.get('to')
print(start,end)#
if start and end:
datetimes = MyModel.objects.filter(invoice__created_at__range=(start,end)).annotate(
total_price=Sum(
(F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3))
).annotate(
total_quantity=(
Count('pk')
)
).aggregate(
all_price=Sum(F('total_price')),
all_qnt=Sum(F('total_quantity'))
)

else:
datetimes = MyModel.objects.all().annotate(
total_price=Sum(
(F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3))
).annotate(
total_quantity=(
Count('pk')
)
).aggregate(
all_price=Sum(F('total_price')),
all_qnt=Sum(F('total_quantity'))
)
return JsonResponse(datetimes,safe=False)
@login_required
def queryTemplate(request):
return render(request,'myapp/datetimes.html')

我知道如何进行查询,但不确定如何将输入的日期类型值发送到后端

这是我的GET表格,从获得两个日期

$(document).ready(function(){
const start_date = new Date($('#from').val());
const end_date = new Date($('#to').val());
console.log(start_date)
console.log(end_date)
if(start_date && end_date){
data={
'from':start_date,
'to':end_date            
}
}
function dateTimePrices(){        
$.ajax({
type:'GET',
url:'/prices/dateTime/data',
data:data,                
success:function(data){
const datetimes = data;
var k = '<tbody>';
if(datetimes){
k+= '<tr>';
k+= '<td>' + datetimes["all_qnt"] + '</td>';
k+= '<td>' + datetimes['all_price'] + '</td>';
k+= '</tr>'                    
}else{
k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple" colspan=6>found nothing</td>'
}
k+='</tbody>'
document.getElementById('datetime_list').innerHTML = k        
}                
})        
}    
dateTimePrices();    
})
<form action="" method="GET">
<div class="col-11 p-1 mt-1 mx-auto text-center row rtl ">
<p class="col-12 col-sm-6 mx-auto text-left row">
from  
<input type="date" class="form-control col-9 mr-1" name="from" id="from"> 
</p> 

<p class="col-12 col-sm-6 mx-auto text-right row">
to
<input type="date" name="to" class="form-control col-9 mr-1" id="to">   
</p>
<button class="btn btn-info col-8 col-sm-5 col-md-3 mx-auto">search</button>
</div> 
</form>
控制台中显示invalid date,后端显示:

django.core.exceptions.ValidationError:[]"无效日期"值的格式无效。它必须为YYYY-MM-DD HH:MM[:ss[.uuuuu]][TZ]格式。']

我非常感谢您的任何想法,提前谢谢。。。

我还必须检查输入日期是否存在,然后将data变量调用到ajax中,但现在即使我没有进行任何搜索,仍然假装日期存在,并从服务器端返回此错误

您需要使用jquery为表单提交添加一个事件处理程序!

$( "#target" ).submit(function( event ) {
alert( "Handler for .submit() called." );
event.preventDefault();
});

最新更新