Unable to load CSS in Django

Having recently started using Django, I encountered an issue with loading CSS files. This is the directory structure in my Windows system:

Scenario 1:

.
|__myproject
      |__+myproject
      |__+myapp
      |__-static
      |      |__-css
      |           |__style.css
      |__-templates
              |__base.html

In base.html:

<!DOCTYPE html>
{% load static %}
<html>
  <head>
    <link rel="stylesheet" href="{% static 'css/style.css' %}"  type="text/css">
  </head>
  <body>
    # ...
  </body>
</html>

In settings.py:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
STATICFILES_DIR = os.path.join(BASE_DIR, "static")

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    STATICFILES_DIR,
]

INSTALLED_APPS = [
    # ...
    'django.contrib.staticfiles',
    # ...
]

TEMPLATES = [
    {
        # ...
        'DIRS': [TEMPLATE_DIR,],
        # ...
    },
]

Despite these settings and configurations, the CSS file cannot be loaded.

However, upon changing the directory tree to the following:

Scenario 2:

.
|__+myproject
|__+myapp
      |__-static
      |      |__style.css
      |__-templates
             |__base.html

In base.html:

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

Now it works perfectly fine.

What exactly was causing the issue in scenario 1? What was missing in that setup?

Answer №1

To implement the necessary changes, make sure to include the following lines within your settings.py file:

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

Answer №2

Your coding style seems a bit inconvenient.

  1. Make sure to start with <!DOCTYPE html>. Then add {% load static %}

2. It's recommended to use different types of quotes, such as (" ") and (' '), for href and static.

3. Remember to include type="text/css" in the link tag like this-

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

In your code, consider that " {% static " and " %} " are two separate strings, causing syntax errors with style.css. Python supports both (" ") and (' ') for situations like this (see text color).

I hope this information is useful. Thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The alignment issue persists in HTML/CSS despite troubleshooting efforts

I am facing a challenge while attempting to center text within a modal window, despite my efforts the text remains uncentered. This is my HTML code: <div ng-init="modalCompassDir()"> <div class="myModal"> <img class='floor ...

The words are located behind the img element once the line is broken

One section of my website features main articles with an image on the left and a description on the right. However, I am facing an issue where the text does not break properly when it reaches the end of the container and ends up behind the image. To better ...

Angular allows for the editing of a table by double-clicking and using an array of objects

I am dealing with an array of objects structured like this: $scope.rows = [{ num1: 56, num2: 78, num3: 89 }, { num1: 56, num2: 78, num3: 89 }, { num1: 56, num2: 78, num3: 89 }, { num1: 56, num2: 78, num3: 8 ...

Is there a way to confine a draggable object's movement to a specific area?

Users have been granted the ability to input their characters onto the screen and manipulate each character's position. However, I only want users to move these characters within a specific square or rectangle area, limiting their placement options. ...

Tips for ensuring that hover:after contents do not impact the positioning of the next element

I have created a photo list section on my webpage. <div id="main_post_photo"> <% for(var q=0;q<resolve.length;q++){ if(resolve[q].images.length>=1){%> <a href='/post/<%= resolve[q]._ ...

CSRF Error Due to AJAX POST Request Following Django Application Deployment on Nginx Server

I have configured Nginx and Gunicorn to deploy my Django 2.X blog on a VPS. When I send data to the Django backend using Jquery AJAX, I encounter a 403 CSRF error. Despite searching extensively, I am unable to resolve this issue. Interestingly, when I re ...

What strategies can flex-shrink use to triumph over padding in the battle for space

I am facing an issue with a flex-box tag cloud where the sizing is controlled from the outside. I need the tags inside to be collapsible all the way down to zero if necessary, but currently they only collapse up to 2 times their padding. https://i.sstatic ...

How do I use jQuery to remove a dynamically added class from the page's header?

When using an inline editor to modify css classes, I encounter the need to remove and then re-add a class definition after making changes. Additionally, users have the option to delete elements, so it's important that the definition is also deleted. ...

Sticky Bootstrap Navbar

I am trying to incorporate a Bootstrap 4 navbar into a div with a background image. My goal is for the navbar to become sticky at the top, resize, and change color as the user scrolls down the page. However, I've noticed that when I place the navbar w ...

Control Over Fluid Grid Layouts

Apologies for reaching out, as I usually try to figure things out on my own. However, after spending hours reading through countless pages with no success, I am at my wit's end. I'm struggling to create a 4-column 'home' landing page f ...

Encircle a circle within the Progress Tracker

Is there a way to create a ring around the circle in this progress tracker, similar to the image shown here? The progress tracker is based on You can view an example here. The CSS approach used was: .progress-step.is-active .progress-marker { backgrou ...

Integrate automatic column spacing in Bootstrap grid system

Is there a way to automatically add spacing between Bootstrap columns? For example, if I have a column with a width of 5 and another with a width of 4, the offset should be 3. How can this be achieved? ...

Unexpected behavior exhibited by form in response to CSS styling

When I try to adjust the values of left, top, and right, nothing seems to change. I also experimented with the position attribute without any success. What could be the mistake on my end? .PHP_A { position: static; left: 200px; top: 400px; righ ...

Incorporating GitHub user emails into Django's social login system

I used the instructions from this tutorial to implement social login on my Django application. Everything is working smoothly, but I encountered an issue with fetching user emails for GitHub users even after adding: SOCIAL_AUTH_GITHUB_SCOPE = ['email ...

Styling a half circle in React Native

Despite my efforts, I have not been able to find anything quite like this: example Could anyone provide guidance on implementing this with react? ...

What could be the reason for the misalignment between md-menu and md-button when ng-href is included in the button?

Check out the demo by clicking here: http://codepen.io/audiodude/pen/vLyNvw The main distinction between the top and bottom sections lies in the fact that the top section utilizes an md-button with an ng-href attribute, which Angular Material compiles int ...

Getting the next sibling element with Selenium: A complete guide

Having trouble targeting a textbox after the label "First Name" in a list to enter a first name. Here's what I've tried: WebElement firstNameLocTry = driver.findElement(By.xpath("//label[text()='First Name']/following-sibling::d ...

Tips for dynamically resizing a div element as a user scrolls, allowing it to expand and contract based on

I was working on a project and everything seemed easy until I hit a roadblock. What I am trying to achieve is expanding a div to 100% when scrolling down to the bottom of the div, then shrink it back to 90% at the bottom and do the reverse when scrolling ...

Deactivate a few CSS guidelines

For my project, I am incorporating interfaces within other interfaces and have been facing conflicts between bootstrap rules and other CSS files. To address this, I encapsulated all Bootstrap rules within a .use_bootstrap class. Now, within my interfaces ...

Progress Bar Has Wandered Off Track

Having trouble with two queries. Take a look at the live view here First Query: Struggling to position the progress bar below my image using CSS. Second Query: Want to make the images slide left instead of fading with the progress bar in my Javascript. ...