Guide to incorporating CSS and JavaScript files in Django using Python

I am currently experiencing issues with loading only static css and Javascript in my Django project. The code I have included is successfully loading image files, but the css and js files are not loading.

 {% load staticfiles %}
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
 <title>Home</title>
 <link href="{% static "pro.css" %}" rel="stylesheet" type="text/css"/>
 </head>
 <body>
 <div id="sd">
 <h1>Hi my first Django application</h1>
 <img src="{% static "images/img08.jpg" %}"/>
 <div id="demo"></div>
 </div>
 </body>
 </html>

and my webpage source in the browser

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Home</title>
<link href="/static/pro.css rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="sd">
<h1></h1> 
<img src="/static/images/img08.jpg"/>
<div id="demo"></div>
</div>
</body> 
</html>

my code in the settings files:

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS=     (os.path.join(BASE_DIR,'questions','static','css'),os.path.join(BASE_DIR,'questions','static','js'),)

Upon checking my Javascript console, I encountered the following error message - 127.0.0.1/:19 Resource interpreted as Stylesheet but transferred with MIME type application/x-css:

Answer №1

  1. For general project static files:

    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    )
    
  2. For static files specific to your apps:

    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    )
    

To access these files in your templates:

{% load static %}

{# Access files in project static directory - tip №1 - static/... #}

<script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script>
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" type="text/css">



{# If your app is named `questions` - tip №2 - questions/static/questions/... #}    

<script type="text/javascript" src="{% static 'questions/js/some.js' %}"></script>
<link href="{% static 'questions/css/pro.css' %}" rel="stylesheet" type="text/css">

Answer №2

Check out this code snippet:

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

Make sure to do the same for JavaScript files as well.

You've included the path for images using static "images/image_name.jpg", but don't forget to do the same for your CSS and JavaScript files.

Answer №4

Having encountered the same issue myself, I was able to find a solution:

  1. First, navigate to the settings in your project file setting.py and locate STATIC_URL.
  2. Take note of the URL specified in STATIC_URL and update it to be the absolute path of your static files. For example, my path looks like
    MySite/MyApp/static/My_App/'static files'
    .
  3. Next, paste the path of your My_app into the STATIC_URL and it should resolve the issue.

Note: Remember to format your path correctly in STATIC_URL as shown below:

/file1/ or `/file1/file2/.../`

I hope this information is helpful.

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

Issue with CRUD functionality: The edit function is not functioning properly, as it does not reflect any changes on the

After attempting to implement an edit method in PHP for CRUD, I encountered an issue. When I click the edit button to execute the query, it redirects me to the show all page without making any changes. {<!doctype html> <?php include 'db. ...

Unable to retrieve a particular file from S3 while utilizing Strongloop

While I am able to upload, delete, and list folders from an Amazon S3 container using Strongloop, I am facing difficulties retrieving a specific file. This is my code: $scope.getS3Files = function(myfolderName){ //need to fetch all zip files in myfolderA ...

Error: JSON parsing failed due to an unexpected character, resulting in null data

Many people have asked similar questions on the same topic, but I have not been able to find a solution for my specific problem. Below is the code snippet that I am working with: $.post("show_search_results.php", {location_name: ""+location_name+"", key: ...

terminate a node-cron task or abort a node-scheduler job

I'm currently working on a nodejs project that involves managing multiple cron jobs. However, I've encountered an issue when attempting to cancel these jobs. Here's the scenario: I have set up several cron jobs using node-cron or node-sch ...

Node interprets string as an object

I encountered the following code: <a class="btn-primary btn" href="/employer/booth/<%= user._id.toString() %>" <% console.log(typeof user._id, user._id) %> target="_blank"> Preview your booth </a> Upon running this ...

Unique: "Best Practices for Setting Angular.js Controller Data Directly in the Code"

In this scenario, I need to initialize the data from an inline script, even though I know how to achieve this using a promise on an http request. Currently, the controller is already defined in the header js: var testModule = angular.module('myTestM ...

Text alignment from the lower edge

Imagine having a title inside an image, positioned near the bottom with a negative margin-top. The issue arises when the text orientation expands from top to bottom as more content is added. Is there a way to reverse this, so that the text div grows toward ...

Javascript is currently facing issues with callbacks not functioning properly in an asynchronous manner

Attempting to execute one function after another in my discord.js code. Here is what I have: function1(function2) async function function1(callback) { var guild = client.guilds.cache.get(config.Server); let channels = guild.channels; fo ...

The node.js system automatically restarts an API call when a timeout occurs

Current Setup: I am using a combination of sails.js for the backend API and React for the frontend. The communication between the frontend and backend is handled by the fetch API. Scenario: Within some of my API endpoints, I need to run an external file ...

After moving a JavaScript application to heroku, the script appears to be nonfunctional

I developed a basic javascript application using mojs, an animation library, and aimed to host it on heroku. To begin with, I attempted the "heroku create" command to deploy the original app on heroku - although the app was accessible, the script did not f ...

Tips for correctly linking JS and CSS resources in Node.js/Express

I have a JavaScript file and a stylesheet that I am trying to link in order to use a cipher website that I created. Here is my File Path: website/ (contains app.js/html files and package json) website/public/css (contains CSS files) website/public/scri ...

Customizing style with state using react and styled-components

As a newcomer to react and styled-components, I find myself in a bit of a mess due to my lack of understanding of how it all functions. Let's start from the beginning. I have a basic page (App.js) that displays two components called "Knobs". Each &ap ...

Vue - a guide on customizing a prop in a parent component

I have implemented a wrapper component that encapsulates a Quasar q-select element in the following manner: <template lang="pug"> q-select( :options="organisations" option-value="id" v-bind="$attrs&quo ...

Incorporating Material-UI with React Searchkit for a seamless user experience, featuring

I encountered an issue when trying to use both searchkit and material-ui in my React application. The problem arises from the fact that these two libraries require different versions of reactjs. Initially, everything was working fine with just searchkit in ...

Here's a unique version: "Strategies for effectively closing a modal when moving to a

I'm currently working with react-router-dom and material UI modal, and I am looking for a way to automatically hide the modal whenever the user navigates to another page. Here is my App component: const App = () => ( <BrowserRouter> &l ...

The HTML div is not aligned in the center even when using flexbox

After creating a list within a centered flex div, it seems that the list is not aligning properly. I used flex on the list-div2 and the translate rule in the parent's middle-text div, but it still doesn't look centered as expected. Can anyone p ...

Looking to have the content aligned in the center of the parent container while also

Below is the code snippet I am working on, which utilizes Bootstrap 4: .resource{ border:1px solid red; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxP ...

Utilizing an external type definition in JSDoc @typedef

I'm encountering an issue with reducing redundancy when defining my imported types. I am trying to streamline the process, but unfortunately I am running into errors. /** @typedef {import("../types/util")} util @typedef {util.mapBehaviors} m ...

Guide to making a toggle button with a Light/Dark mode functionality

I have implemented a light/dark toggle button and now I want to integrate the functionality for switching between light and dark themes on my webpage. The switch should toggle the theme between dark and light modes when clicked. Some basic styling has been ...

Explore our array of images displayed in an interactive gallery featuring clickable

I have a query I'm facing an issue with my code. Currently, I have a gallery that displays images perfectly. Now, I want to enhance it by showing a larger resolution of the image when clicked. However, when I add the href tag to link the images, they ...