Search code examples
htmlcssdjangobackground-image

CSS Background Image not displaying within Django framework


Following the Polls Webapp tutorial in Django. Keep receiving a 404 error through my command line and my image icon is displayed, but not the image itself.

Tried changing the path a couple times, resetting the static migration, and changing my static root. Still no image.

Here is my style.css

li a {
    color: green;
}

body {
    background-image: url('static/images/background.png') no-repeat;
}

Here is my index.html

{% if latest_question_list %}
    <ul>
        {% for question in latest_question_list %}
        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a>
        </li>
    {% endfor %}
</ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

{% load static %}

<link rel="stylesheet" href="{% static 'polls/style.css' %}">

<img src="{% static 'static/images/background.png' %}" alt="My Image">

Here is some of my settings.py

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


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

Anyone have an idea?


Solution

    1. It's better to add :link and/or :visited to the selector (anchor tag)
    2. Add forward slash (/) to the beginning of the url value of the property background-image.
    li a:link,
    li a:visited {
        color: green;
    }
    
    body {
        background-image: url('/static/images/background.png') no-repeat;
    }
    
    1. remove static/ from the img src.
    {% load static %}
    
    <link rel="stylesheet" href="{% static 'polls/style.css' %}">
    
    <img src="{% static 'images/background.png' %}" alt="My Image">
    
    {% if latest_question_list %}
        <ul>
            {% for question in latest_question_list %}
            <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a>
            </li>
        {% endfor %}
    </ul>
    {% else %}
        <p>No polls are available.</p>
    {% endif %}
    
    1. Remove forward slash (/) from STATIC_URL and add STATICFILES_DIRS in settings.py

    settings.py:

    STATIC_URL = 'static/'
    
    MEDIA_URL = '/images/'
    
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'static'),
    ]
    
    MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
    STATIC_ROOT = os.path.join(BASE_DIR, 'media')
    
    1. Make sure you updated urlpatterns in urls.py

    <project_name>/urls.py:

    from django.contrib import admin
    from django.urls import path, include
    
    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        ...
    ]
    
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)