'Get relative path in Django

I've created a map where I want to implement some kml files into it . If i harcode the url it works but im trying to pass it through a variable because Im dealing with many kml files in a for loop. Even though the url path im getting in console is right i dont get the result i need.Any idea how to fix that?

view:

def map(request):
    field_list = models.Field.objects.all()
    context = {
        "title": "Map",
        "field_list": field_list,
    }
    template = 'agriculture/map.html'
    return render(request, template, context)

If i hardcode the url it goes like this :

var polygon = omnivore.kml("{% static '../media/kml/user_admin/2022-04-07-2-Arnissa_cherry.kml' %}", ... );

I've tried doing it like this but even though the path Im getting is correct it seems django does not read the path(kml is the FileField in my model):

map.html

{% for field in field_list %}
    $(".search_area").append(new Option("{{field.friendly_name}}")); //friendly name 
   
var kmldir = "../media/" + "{{field.kml.name}}"
console.log(kmldir) // ../media/kml/user_admin/2022-04-07-2-Arnissa_cherry.kml

var polygon = omnivore.kml("{% static 'kmldir' %}", null, new L.GeoJSON(null, { //file url
    style: function() {
        return {
            color: 'red',
            transparent: true,
            opacity: 1,
            fillOpacity: 0.05
        }}     
}));  
kml_arr.push([polygon, "{% static 'kmldir' %}"]); //file url
{% endfor %}


Solution 1:[1]

I tried a different approach and it worked

{% for field in field_list %}

    {% with "../media/"|add:field.kml.name as fieldname %}       

        $(".search_area").append(new Option("{{ field.friendly_name }}")); //friendly name 

         var polygon = omnivore.kml('{% static fieldname %}', null, new L.GeoJSON(null, { //file url
            style: function() {
                return {
                    color: 'red',
                    transparent: true,
                    opacity: 1,
                    fillOpacity: 0.05
                }
            }
        }));

             kml_arr.push([polygon, '{% static fieldname %}']); //file url
    {% endwith %}

{% endfor %}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 haduki