weixin_33717298 2018-09-20 17:27 采纳率: 0%
浏览 56

Django-发出Ajax请求

Im having a hard time figuring out how to integrate this ajax request into my view. I'm still learning how to integrate django with ajax requests.

My first question would be: Does the ajax request need to have its own dedicated URL?

In my case I am trying to call it on a button to preform a filter(Preforms a query dependent on what is selected in the template). I have implemented this using just django but it needs to make new request everytime the user preforms a filter which I know is not efficient.

I wrote the most basic function using JQuery to make sure the communication is there. Whenever the user changed the option in the select box it would print the value to the console. As you will see below in the view, I would to call the ajax request inside this view function, if this is possible or the correct way of doing it.

JQuery - Updated

$("#temp").change( function(event) {
    var filtered = $(this).val();
    console.log($(this).val());
    $.ajax({
        url : "http://127.0.0.1:8000/req/ajax/", 
        type : "GET", 
        data : { 
            'filtered': filtered
        }, 
        dataType: 'json',

        success: function(data){
            console.log(data)
        },
        error: function(xhr, errmsg, err){
            console.log("error")
            console.log(error_data)
        }
    });

Views.py

def pending_action(request):
    requisition_status = ['All', 'Created', 'For Assistance', 'Assistance Complete', 'Assistance Rejected']
    FA_status = RequisitionStatus.objects.get(status='For Assistance')

    current_status = 'All'
    status_list = []

    all_status = RequisitionStatus.objects.all()
    status_list = [status.status for status in all_status]

    # This is where I am handling the filtering currently
    if request.GET.get('Filter') in status_list: 
        user_req_lines_incomplete = RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status=request.GET.get('Filter')))
        current_status = request.GET.get('Filter')
    else:
        user_req_lines_incomplete = RequisitionLine.objects.filter(parent_req__username=request.user).exclude(status__status='Completed')

    user_reqs = Requisition.objects.filter(par_req_line__in=user_req_lines_incomplete).annotate(aggregated_price=Sum('par_req_line__total_price'),
                                                                                                header_status=Max('par_req_line__status__rating'))
    return render(request, 'req/pending_action.html', { 'user_reqs':user_reqs, 
                                                        'user_req_lines_incomplete':user_req_lines_incomplete, 
                                                        'requisition_status':requisition_status, 
                                                        'current_status':current_status,
                                                        'FA_status':FA_status}) 

def filter_status(request):
    status = request.GET.get('Filter')
    data = {
        'filtered': RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status=status)),
        'current_status': status
    }
    return JsonResponse(data)

Urls.py

path('pending/', views.pending_action, name='pending_action')
  • 写回答

1条回答 默认 最新

  • weixin_33670786 2018-09-21 17:04
    关注

    First: you have to divide your template to unchangeable part and the part that you want to modify with your filter.

    Second: for your goal you can use render_to_string. See the followning link https://docs.djangoproject.com/en/2.1/topics/templates/#usage

    code example (views.py):

    cont = {
        'request': request, #important key-value
        'your_models_instances': your_models_instances
    }
    html = render_to_string('your_filter_template.html', cont)
    return_dict = {'html': html}
    return JsonResponse(return_dict)
    

    In your js file you need to determine relative url "{% url 'name in yours url file'%}" And in success you need to add next line:

    success: function(data){
      $(".filter-block").html(data.html);
    }
    

    i hope it will help you! Good luck!

    评论

报告相同问题?

悬赏问题

  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问