Save leaflet marker in django model

I want to create a web app with django where user can create marker on a map. I have this js script to add marker by clicking on a leaflet map.

window.onload = function () {
    element = document.getElementById('osm-map');
    var markers_list = new Array()
    var map = L.map(element);
    let rm = false
    
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
    // var markers = L.featureGroup([])
    var target = L.latLng('48.8686034651125', '2.34261607443957');
    map.setView(target, 5);

    map.on('click', function (e) {
        var node = document.createElement("LI")
        var marker = new L.marker(e.latlng).addTo(map);
        markers_list.push(marker);
        var marker_id = marker._leaflet_id
        let title_marker = window.prompt("give a name to your marker",marker_id);
        //todo make sure input is not empty
        while (!title_marker){
            title_marker = window.prompt("give a non empty name",marker_id);
        }
        marker.bindPopup("marker's info: "+title_marker).openPopup()
        map.addLayer(marker)
        a = document.createElement('a')
        a.innerHTML=title_marker
        a.setAttribute('id', marker_id)
        a.setAttribute('href',"javascript:void(0);");
        node.appendChild(a);
        document.getElementById("marker-list").appendChild(node)
        }
    );

    rm_btn.onclick = function () { // function to enable edit of marker
        rm = !rm
        if (rm) {
            document.getElementById('rm_btn').innerHTML = "Edition enabled";
        }
        else {
            document.getElementById('rm_btn').innerHTML = "Edition disabled";
        }
    }
    
        var ul = document.getElementById('marker-list'); //list of li marker
        ul.onclick = function(e) {
            if (rm) {
            id_to_rem = e.target.id
            for(var i=0;i<markers_list.length;i++){// iterate over layer to remove marker from map
                if (markers_list[i]._leaflet_id == id_to_rem){
                    map.removeLayer(markers_list[i])
                }
            }
            var a_list = ul.getElementsByTagName('a')
            for(var i=0;i<a_list.length;i++){// iterate over ul to remove marker from li
                if (a_list[i].id == id_to_rem){
                    ul.removeChild(ul.childNodes[i+1])
                }
            }        
        };
    }   
}

Markers are saved in the marker-list array. How is it possible to save theses markers in a django model. Do I have to put a script tag in the html template then do some django stuff or is there another solution ?

Thanks

Your question is quite broad. So instead of writing the code for all the various parts that are needed (model, view, url, template, js script) I will provide an outline, which you can use to further narrow down the problem.

Depending on your application logic and your preferences, your data should be submitted either using AJAX or as a form submit. Use AJAX if you need the data submitted without a "page refresh". If there is no final submit action by the user, then AJAX will certainly be better from an user experience perspective.

AJAX

There're many resources online that explain how to use AJAX with Django. For example,

Also look at the detailed Django documentation on how to include the CSRF token in an AJAX request.

One decision you have to make is whether you want to send the data with a form or not. If you send the data without the form, make sure you handle the validation properly. Sending the data with a form has the advantage that Django takes care of form validation, sanitization etc.

If you want to use a form, you could include the form in your html with hidden fields and fill those fields with JS as the markers are set. You'll probably need a dynamic formset, since the number of markers is not fixed. Then you can use FormData to serialize the form fields and send the serialized data to your Django backend, which can then handle the data in the standard way.

Without AJAX

In this case you do the same thing as above (populate the hidden fields with the marker data), but instead of submitting the request via AJAX, there would be e.g. a standard submit button.

Back to Top