Search code examples
django-templatesleafletdjango-staticfiles

Not found custom icon in static files


I am using custom pin icon for map (based on leaflet), the custom icon file mixed.png is located in static/icons/. Part of template index.html looks like:

<script>
        // JavaScript code to initialize and populate the map with trash points
        // You will need to use the appropriate map library and API key (if required)
        // For example, with Leaflet and Django template tags

        var map = L.map('map'); // Set initial map view

        // Add your map tiles (e.g., OpenStreetMap, Mapbox, etc.)
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);
        
        var markers = [];
        var bounds = [];

        // Iterate through the trash_points and add markers to the map
        {% for trash_point in trash_points %}
        
        **var iconUrl = "static/icons/" + "{{ trash_point.category.name|lower }}.png"**;
        var customIcon = L.icon({
            iconUrl: iconUrl,
            iconSize: [32, 32],
            iconAnchor: [16, 32],
        });

            var marker = L.marker([{{ trash_point.location.y }}, {{ trash_point.location.x }}], {icon: customIcon}).addTo(map);
            markers.push(marker);
            bounds.push([{{ trash_point.location.y }}, {{ trash_point.location.x }}]);
            // You can customize the marker icon, popup, etc. based on your needs
        {% endfor %}

        // Create a layer group from the markers and add it to the map
        var markerGroup = L.layerGroup(markers).addTo(map);

        // Fit the map to the bounds of the marker group
        map.fitBounds(bounds);
    </script>

Parts of settings.py look like:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Urls look like:

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('trash.urls')),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I see following error on a site, when oppening main page:

GET http://localhost:8000/static/icons/mixed.png 404 (Not Found)

How can i solve that and see custom icons?

I collected static and open site through py manage.py runserver. Important part: mediafiles work correctly!


Solution

  • Icons didn't collect with another static, because they were put in directory /static on the layer of project (not app). So django didn't collect static from this folder, because it collects static to this folder. I just put icons in other folder on the layer of app.