How to change a queryset for xhtml2pdf via ajax

陌路散爱 提交于 2020-04-17 21:30:46

问题


im trying to build a function where by the user is able to select the items he wishes to render to pdf. In order to do this, i first did some code to store the PK of the items the user selected.

(javascript)

var arr = []
function selector(clicked_id){
    var a = clicked_id
    if (arr.includes(a) === false){
    arr.push(a)
    document.getElementById(a).classList.add('bg-light');
    } else {
    const index = arr.indexOf(a)
    arr.splice(index, 1)
    document.getElementById(a).classList.remove('bg-light')
    }
    console.log(arr)
    console.log(a)

    };

(html)

        {%for trial in trials %}
    <td style="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" align="center" valign=middle bgcolor="#CCFFFF" id={{trial.trial_id}} onClick="return selector(this.id);"><b><font face="Arial" size=1>
    </td>
    {%endfor%}

As such , clicking onto the table cell will change the color of the cell and save the pk into an array. When the user clicks the button to generate the pdf , i wil pass the list of pk through into an ajax function as such :

function ajaxsender(clicked_id){
$.ajax({
 url : "{% url 'bom-pdf'%}",  
 method : "POST",
 data : {
   'csrfmiddlewaretoken' : "{{  csrf_token  }}",
    'arr' : arr
          },
 success : function(result) {
    console.log(arr)
    }

})};

(HTML)

        {% for product in product %}
    <a {% url 'bom-create' product.formulation_id %} id = {{product.formulation_id}} onClick="return ajaxsender(this.id);" class='btn w3-teal float-right' style="margin-right:3%">Generate BOM PDF</a>
    {% endfor %}

This is the view handling the requests:

def BomPdf(request):
  if request.method=='POST' and request.is_ajax():
    print('ajax requessssst')
    listy = request.POST.getlist('arr')
    print(type(listy))
    #some code here to be able to filter out my data based on the queryset passed in#
     pk = #
     data = {
         'product' : ProductFormulation.objects.filter(formulation_id = pk)[0],
     }
     pdf = render_to_pdf('rnd/bom_pdf.html', data)
     return HttpResponse(pdf, content_type='application/pdf')

The tricky part is that im using xhtml2pdf to render into a pdf , as such there is a need to retunr a httpresponse , instead of a typical jsonresponse that a view handling ajax would do. Because of this im facing a 405 error which seems to be something related to a cors error Therefore i have 2 questions :

  1. how does one do a query using ajax and pass that into a context ?
  2. how do i apply the concept in my case?

来源:https://stackoverflow.com/questions/60119033/how-to-change-a-queryset-for-xhtml2pdf-via-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!