Search code examples
djangodjango-templatesdjango-urlsdjango-static

DJANGO : Problem of mixing between URL of web pages and media files


I'm developing a website and sometimes I have a strange problem : the URL of the page is concatened with the URL of the images on this page, which means I cannot access to these images. It's a bit hard to explain so here is an example :

I have a view called "mes_plats" that displays some informations about meals cooked by a cooker. The informations are displayed with a background located at static/media/img_background.jpg and everything works correctly. I have another view called "supprimer_plat" (url : supprimer-plat) whose purpose is to delete the informations about a particular meal. This view render the same html template as the other one but this time the template try to access the following url for the background : supprimer-plat/static/media/img_background.jpg. Obviously the background isn't displayed. So my question is, why does the url of the page concatened to the URL of the image in one case and not in the other ? And how can I solve it ? Thanks in advance !

views.py

def mes_plats(request):
    return render(request, 'actualites/mes_plats.html', {'my_meals': Plat.objects.filter(chef=request.user.useradvanced.chef, date_prep__gte = date.today())})

def supprimer_plat(request, id):
    plat = get_object_or_404(Plat, id=id)
    plat.delete()
    return render(request, 'actualites/mes_plats.html', {'my_meals': Plat.objects.filter(chef=request.user.useradvanced.chef, date_prep__gte = date.today())})

urls.py

urlpatterns = [
    path('mes-plats', views.mes_plats, name = 'mes-plats'),
    path('supprimer-plat/<int:id>', views.supprimer_plat, name = 'supprimer-plat'),
]

mes_plats.html

<!doctype html>
{% extends "base.html" %}
{% load static %}
{% block content %}
   <body class="view" style="background-image: url('static/media/img_background.jpg'); background-repeat: no-repeat; background-size: cover; background-position: center center;">
      SOME CODE
{% endblock %}

Solution

  • This is expected behavior. Your url is:

    static/media/img_background.jpg
    

    uses a relative path. So if the site is located at foo.com/bar/qux, then it will browse for foo.com/bar/static/media/img_background.jpg.

    You thus can avoid that by prepending the path with a slash, like:

    /static/media/img_background.jpg

    But it might be better here to make use of Django's staticfiles support [Django-doc]. After configuring this, you can use the {% static … %} template tag [Django-doc] to "calculate" the urls.

    Note that in deployment mode, you will need to configure your server to serve the static files itself. But you can still use the {% static … %} to calculate the URLs, and thus make it less likely to make mistakes.