【问题标题】:how to send input date value from template to backend through ajax request - django如何通过ajax请求将输入日期值从模板发送到后端 - django
【发布时间】:2022-01-17 12:00:33
【问题描述】:

我必须基于两个日期进行查询,如果日期存在,如果不只是运行查询而不进行任何过滤,但我不知道如何将日期输入值从客户端发送到服务器端,这是我的意见

 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: ['“Invalid Date” value 的格式无效。它必须是 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] 格式。']

我非常感谢您的任何想法,在此先感谢您...

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

【问题讨论】:

  • 确保您传递的数据是有效的,它应该与上述错误中指定的格式匹配。
  • @Sumithran 但也在控制台中返回无效日期
  • @Sumithran 我也试过这个,但不起作用new Date($('#from')).toLocaleDateString("fr-CA")

标签: json django ajax date


【解决方案1】:

您需要为使用 jquery 提交的表单添加event handler

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

【讨论】:

  • 请问怎么做,我不擅长js
  • 更新了我的回复
  • 是的,我做到了,但不知道如果存在两个日期,如何将其发送到服务器端
  • 在您的代码中,您将在 document.ready 中获取日期,但这应该在 form.submit
  • 所以流程应该是: - 事件触发时监听表单提交事件: - 获取字段 -​​ 发送 AJAX 请求
猜你喜欢
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
  • 2015-11-07
  • 2016-02-28
  • 2021-02-14
  • 1970-01-01
  • 2014-09-15
相关资源
最近更新 更多