The application of styles was ineffective on the Django Project once it was uploaded to Render

My attempt to upload my django project to Render has hit a snag. The project includes numerous HTML files and CSS styles, with the latter being stored in a file named 'styles.css' within the static folder. Upon running the project, I noticed that while the images load properly, the styles seem to be missing from everything, including the Django Admin panel. The console indicated an issue with the MIME type when trying to load the stylesheet. A similar problem arises with my main.js file, also residing in the static folder. I have heard about using gunicorn, which is installed on my system, but I am unsure if it's the root cause of this problem as the images display correctly (albeit with varying sizes). I am seeking advice on how to resolve this issue.

To provide context, here is how I configured the media and static URLs in my settings.py:

STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR / 'static']

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

This is my current urls.py for the primary project:

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),
    path('', include('store.urls')),
    path('chatbot/', include('chatbot.urls')),
]

urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

The base.html template I am utilizing, containing links and script tags in its header, looks like this:

{% load static %}
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
  <link rel="stylesheet" href="{% static 'style.css' %}">
  <!-- jquery -->
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91f3fefee5e2e5e3f0e1d1a4bfa2bfa2">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
  
  <!-- custom css & js -->
  <script src="{% static 'main.js' %}" defer></script>
  <link rel="shortcut icon" href="{% static 'favicon.ico' %}">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <title>U-Community Mart</title>

</head>


<body class="body-main">
{% include 'navbar.html' %}
{% if messages %}
    {% for message in messages %}
        <div class="alert alert-info alert-dismissible fade show" id="message" role="alert">
          {{message}}
        </div>
    {% endfor %}
{% endif %}
  <div class="container" style="margin-top: 50px; margin-bottom: 0; margin-left: auto; margin-right: auto;">
    {% block content %}
    {% endblock content %}
  </div>

  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0d2dfdfc4c3c4c2d1c0f0859e839e83">[email protected]</a>/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
    crossorigin="anonymous"></script>

</body>

</html>

UPDATE: Following some modifications primarily in the settings.py file, such as installing whitenoise, I encountered some progress.

STATIC_URL = '/static/'
if not DEBUG:
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
    STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

I also inserted 'whitenoise.middleware.WhiteNoiseMiddleware' right after the SecurityMiddleware. At present, the Django admin panel seems to load the correct styles. However, I am still facing challenges when attempting to load the CSS and JS files. Here are the adjustments made in the HTML:

<link rel="stylesheet" type="text/css" href="static/style.css">
  <script src="static/main.js" defer></script>

It appears that the problem may lie in the URL configurations, but I remain uncertain about how to tackle it.

UPDATE 2: Fortunately, I managed to overcome the issue. As per my findings, Render accesses all static files in a separate folder named 'staticfiles'. While I had created the folder, it was empty. To address this, I added the following to the settings:

STATIC_URL = '/static/'
if not DEBUG:
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
    STATICFILES_STORAGE = 
    'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Subsequently, I executed python manage.py collectstatic. This action ensured that all static files were now located in the folder required by Render. I appreciate any feedback provided here, and hope this solution proves helpful to others contemplating deploying their django projects on Render.

Answer №1

Consider removing the backslash "/" from the STATIC_URL in the code block before the last one you provided. In the initial code block, it is set as:

STATIC_URL = 'static/'

Contrast this with the second to last code block:

STATIC_URL = '/static/'

In my own projects, I have found that the correct line should be:

STATIC_URL = 'static/'

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

Use the CSS class

To create tables with 3 rows and 2 columns using divs, I have utilized the ng-repeat directive. Within this setup, there are two CSS classes - red and green, that need to be applied in the following manner: - Red class for the 1st column of the 1st row - ...

Looking for ways to incorporate both external and internal styling using jQuery and CSS in my template?

I've been working on a django project for a while now, and I'm facing some challenges with getting external and internal CSS to work. Only inline CSS seems to be functioning properly. I have two questions: How can I get external or internal C ...

Is there a way to transfer driver information between methods smoothly?

Just started working with Selenium and I have a query. I created a method called urlload to load a specific URL, but when I try to read webElements of the webpage loaded in that method from another class, it doesn't seem to work. Any advice or hel ...

Pattern matching in JavaScript using regular expressions is used to identify and extract repeating patterns,

There is a specific string that contains structured data and multiple instances of @doc { within it. I need to extract these occurrences, making sure the result includes two unique matches. To achieve this, regular expressions come in handy: var matches = ...

Collapsible feature in Bootstrap malfunctioning after initial use

I am currently developing a website using PERSONA as the CMS and have implemented collapsible elements on the page using Bootstrap. The website is using Bootstrap Version 3.3.7 and PERSONA includes an internal version of jQuery. For reference, you can acce ...

The H1 tag is mysteriously displaying padding or margin on the bottom, despite not being set

Despite not setting any padding or margin for the H1 tag, it still appears to have some spacing at the bottom. After applying a margin and padding of 0 to both the h1 tag and the text below it, I am still facing an issue where the text doesn't align ...

What could be causing the unequal sizes of my flex children?

After some investigation, I have discovered that the issue I'm experiencing only occurs on certain devices, indicating it may be related to the viewport size. In the code provided, the parent element has a fixed height and width, while the children a ...

How can I make the central element of my site stand out as dominant when I have three vertical elements evenly divided on full screen?

Is there a way to make the central element take up all the viewport space when the screen is minimized or dragged halfway, with the two side elements being purely aesthetic? I'm wondering if CSS or jQuery has any attributes that can accomplish this. ...

Creating a jQuery plugin that allows for multiple plugin calls with customizable settings

Here is a jQuery plugin that I created: (function($){ $.fn.myPlugin = function(options) { if (!this.length) { return this; } var settings = $.extend(true, {}, $.fn.myPlugin.defaults, options); $w=$(this); $w.bind("click ...

What is the method for sending data in Django Rest Framework using function-based views?

Just getting into the world of django rest framework (DRF) and I've mastered using function based views (FDV) with the GET method. However, I'm struggling to figure out how to use the POST method to insert data into the database. # app/models.py ...

Is there a way to utilize DOM in javascript to retrieve list values?

I am looking to retrieve an array or simple string values containing the items in an <ul> element. Below is my code snippet: <!DOCTYPE html> <html> <head> </head> <body> <h2>Unordered List with Disc Bullets</h ...

Guide on Importing All Functions from a Custom Javascript File

As a beginner in learning Angular, I am faced with the task of converting a template into Angular. However, I am struggling to find a solution for importing all functions from a custom js file into my .component.ts file at once. I have already attempted t ...

What could be causing the function to return undefined when using fetch, axios, ajax, or a promise?

When using asynchronous calls, the issue arises where the response is returned as undefined instead of the expected data. This problem can be seen in the following scenarios: Using Fetch const response = getDataWithFetch(); console.log(response); fun ...

Creating pathways in AJAX with Rails

Issue at hand: undefined variable article_id. The objective: Setting up the correct route for AJAX and Rails. What I require: The format articles/1/comments/2. Main goal: To specifically load comment through AJAX, not article. In the current AJAX scrip ...

Pass the result of the callback function from the service to the component

I have integrated the WifiWizard Plugin into my Ionic 2 mobile app using Cordova. It works perfectly fine when I run it in the *.ts file of my page. Here is how my code looks: Declaring WifiWizard before @Component: declare var WifiWizard:any; Using Wif ...

Navigating with Angular Routes leads to a 404 error page

I am facing an issue where Angular is unable to find the content on valid links and returns a 404 error. Below is the configuration of the routes: $routeProvider.when('/', {templateUrl: 'partials/home.html'}); $routeProvider.when(& ...

The node-vibrant module in combination with React

Hey there, I'm currently attempting to display the hex color of a react Component using node-vibrant. (The node package is already installed) It works perfectly when executed with node from the console. |- file.js |- image.jpg file.js // I am havi ...

What is the best way to transfer the "user" object from TopBar.js to App.js in my project?

In my project, TopBar.js functions as an AppBar component responsible for handling user authentication. When a user logs in, I receive an object called "user". My goal is to export this "user" object to App.js. If I am successful in exporting it to App.js ...

Text color-coded for specific hues

I am looking to change the color of a specific text within HTML/PHP/CSS/JS code. Here is an example of the text structure: @john please move the invite to the next week. My goal is to make the word "@john" appear in green, while keeping the rest of the ...

Creating a customer and processing payments with React Stripe including order and shipping details

I implemented a Stripe payment page using Gatsby, React, and AWS Lambda. However, the code is not correctly capturing customer data such as shipping address and email. AWS Lambda Code: const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY); mod ...