Passing objects from Django to Javascript DOM

前端 未结 14 1156
野的像风
野的像风 2020-12-04 21:26

I\'m trying to pass a Query Set from Django to a template with javascript.

I\'ve tried different approaches to solve this:

1. Normal Approach - Javas

14条回答
  •  难免孤独
    2020-12-04 22:19

    Be careful on also making sure that you output JSON data correctly from Django, otherwise all trials on the frontend side will be a waste of time. In my case I could not use JsonResponse as part of the render function so I did the following:

        def view(self, request):
    
            data = []
            machine_data = list(Machine.objects.filter(location__isnull=False).values_list('serial', 'location', 'customer__name'))
            data.append({
                "locations": machine_data,
            })
    
            return render(request, 'admin/company/device/map.html', {
                "machines": data
            })
    

    And on the frontend:

    {% block content %}
    
        {{ machines_with_location|json_script:"machineLocationData" }}
    
        

    Title

    {% endblock %}

提交回复
热议问题