Using React in existing Django Project

I have an existing Django project. Its a website that displays a map with leaflet. Markers and everything is loaded dynamically from django. Now I want to enhance that with React. In a sense that when you click a marker on the map, react will render based on marker_id the specific marker-details in a sidebar or something. I am not sure how to do that. In the django template I have a onclick event to get the marker-details:

                    marker.uri = `/map/api/marker_details/?marker_id=${marker.marker_id}&marker_type=${marker.marker_type}`
                    marker.on('click', function (e) {

                        jQuery.get(this.uri);

                    });

Since this is all in django template and not in React, the result is probably not accessible via react to render the details. Do I have to implement the map with the marker and everything in React to then be able to render the details via API? What am I missing?

If I understand what you ask correctly, what might work is to just send the marker_id in your jQuery. Then, you can get the entire Marker object, with all it's details and send it back to the jQuery, where you can take it apart any way you wish.

from django.http import JsonResponse

def some_view(request, marker_id):
    data = list(Marker.objects.filter(marker_id=marker_id).values())  # wrap in list(), because QuerySet is not JSON serializable
    return JsonResponse(data, safe=False)  # or JsonResponse({'data': data})

Now, instead of just going to the uri, you need to process what it receives, which you can do with:

marker.uri = `/map/api/marker_details/?marker_id=${marker.marker_id}`

marker.on('click', function (e) {
    jQuery.get(this.uri, function(data) {
        alert( "Data Loaded: " + data );
    });
});

Of course, here, it's just an alert with the data you get back, but I think you've already worked out the rest.

Вернуться на верх