[Django]-Django template extends does not call CSS

6👍

Your stylesheet links are all relative URLs, where they should be absolute:

<link href="/static/css/bootstrap.min.css" rel="stylesheet">

note the initial slash.

You should though be using the static tag, after doing load static:

<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet">

1👍

I would suggest using the static tag for maintainability in the future. You currently have the full path defined for example:

<link href="static/css/bootstrap.min.css" rel="stylesheet">

While this might work it is not best practice. You mentioned using {% load static %} which is actually the preferred method to link static files like CSS, javascript, and image files. And once you become used to and comfortable with this method you will find that is in fact easier to implement, less likely for errors (i.e. making a typo in the full path), and makes for more efficient debugging.

Here is a simple example to demonstrate this idea:

#base.html template
<!DOCTYPE html>
{% load static %}
<head>

<!-- meta settings and other code that you have within your head tag -->

<link href="{% static "css/boostrap.min.css" %}" rel="stylesheet">

<!-- rest of your content here -->
</head>

Now this assumes within your static directory that you have a directory named css where you have your CSS files located. Also, it is important to note that despite having {% load static %} within your base.html you are still required in every template that extends base.html to include {% load static %} directly underneath your {% extends base.html %} if you wish to link any static files within your static directory (e.g. CSS, JS, images) in that specific template.

👤alacy

Leave a comment