0

I'm trying to load my json response into my template but when i check it into my console returns undefended !

@login_required
def booking_detail_lists(request,id):
    obj = get_object_or_404(Booking.objects.annotate(no_persons=Count('takes_by')),id=id)
    bookingvisitors = BookingVisitor.objects.filter(booking=obj) 
    doc = Document.objects.filter(booking=obj)
    documents = []
    for i in doc:
        documents.append({
            'source':i.docs.url
        })
    visitors = []
    for i in bookingvisitors:
        visitors.append({
           'full_name':i.visitor.full_name,
           'reason':i.reason,
           'check_in_vis':i.check_in_vis.strftime("%Y-%m-%dT%H:%M"),
           'check_out_vis':i.check_out_vis.strftime("%Y-%m-%dT%H:%M"),
           'admin':i.admin.username,
           'date':i.date.strftime("%Y-%m-%dT%H:%M")
    })
    data = {
        'check_in':obj.check_in.strftime("%Y-%m-%dT%H:%M"),
        'check_out':obj.check_out.strftime("%Y-%m-%dT%H:%M"),
        'taker':obj.taker,
        'phone':obj.phone,
        'no_person':obj.no_persons,
        'id':obj.id,
        'takes_by':visitors,
        'images':documents,
    } 
    json_data = json.dumps(data)

    return render(request,'booking/booking_detail.html',{'data':json_data,'obj':obj,'id':obj.id})  

urls.py

path('ajax/booking/<int:id>',booking_detail_lists , name='booking_detail_lists'),

my html template and ajax

$.ajax({
    type:'GET',
    url:"{%url 'booking:booking_detail_lists' id=2222 %}".replace(/2222/,parseInt({{id}})),
        success:function(data){
            console.log(data.data)

        }
    })
<!--some html tags-->

but in the browser console returns undefinedbut when i just type {{data}} it show as i expected ?! thank you for your recommendation ..

artiest
  • 554
  • 5
  • 20

1 Answers1

0

in the function booking_detail_lists, you are returning render('<template_name>', {<Data for rendering in the template>})...

When you're calling this URL with ajax, actually the template booking_detail.html is returned, which is not in the json format, but the html one.. And this response doesn't have property data (which you're calling with data.data)..

JsonResponse

For the json response from django view, you need to use JsonResponse from django.http

  • Change your function to include this
    # ...Rest Imports
    from django.http import JsonResponse
    
    @login_required
    def booking_detail_lists(request, id):
    
      # ...Processing and generation of data
    
      return JsonResponse({'data':json_data,'obj':obj,'id':obj.id})
    
Anonymous
  • 1
  • 1
  • 2