Django Polls App: Background Image Not Loading

Viewed 187

I am learning Django and building out the first test poll app but am running into issues with the background images. The green text works, but adding the background image does not do anything (background is just white). Any idea why this is not functioning properly?

Background Image C:\Users\xxx\Python\Django\mysite\polls\static\polls\images\sample123.jpg

Style CSS: C:\Users\xxx\Python\Django\mysite\polls\static\polls\style.css

li a {
    color: blue;
}

body {
        background: url('C:\Users\xxx\Python\Django\mysite\polls\static\polls\images\sample123.jpg');
        background-repeat: no-repeat;
         }

Index HTML: C:\Users\xxxx\Python\Django\mysite\polls\templates\polls

{% load static %}

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

{% 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 %}
4 Answers

This should do the trick

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

Your background image is not rendering because, for the background image, you are providing the relative path. Either provide the absolute path or use a static template tag.

body {
    background: white url({%static 'polls\images\sample123.jpg'%}) no-repeat;
}

Try adding this to your polls/urls.py file

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


urlpatterns = [
    #....
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #with out this, the images will not be displayed

and this in your polls/settings.py file

STATIC_URL = '/static/'
MEDIA_URL = '/static/images/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images/')

Try this:

background-image: url("C:\Users\xxx\Python\Django\mysite\polls\static\polls\style.css") no-repeat; 
Related