Utilizing Django's ManifestStaticFilesStorage for efficient management of static files and incorporating imports directly

The latest version of Django (3.2) introduced a feature called ManifestStaticFilesStorage, which adds a hash value to JavaScript files that are called from a template. While this works correctly for direct script references, it doesn't affect imported JavaScript files within those scripts. The ManifestStaticFilesStorage documentation mentions how this hashing is done for CSS files, but there is no clear instruction on achieving the same for JavaScript files. Any ideas on how to make this work seamlessly?

For instance, consider the following line in an HTML template:

<script src="{% static 'myapp/js/myjavascript.js' %}" type="module"></script>

In the browser, this line is transformed as expected:

<script src="/static/myapp/js/myjavascript.12345abc.js" type="module"></script>

However, inside the 'myjavascript.js' file, any imported JavaScript files remain unaffected, potentially leading to cached versions being used instead of updated ones.

import {func1, func2, func3} from './javascript_helper_lib.js';

Answer №1

My solution takes a unique twist on the problem at hand. Instead of utilizing ManifestStaticFilesStorage, I opted for StaticFilesStorage and adjusted the location of the static files directory during the code deployment process.

Prior to deploying the code, I generate a file named /path/to/static_dir_location. Within this file lies solely the path to the actual static files directory, which typically includes details like the application name and release number such as myapp_12345. Subsequently, the static dir location is appended to the STATIC_URL variable within settings.py:

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

with open('/path/to/static_dir_location','r') as file:
    staticdir = file.read().replace('\n', '')

STATIC_URL                  = '/static/{}/'.format(staticdir)

This method compels the browser to reload all static files without necessitating any manual inspection or alteration of file contents. It's worth noting that initial page load times may be extended when users visit the site following an update to the static files, so this approach may not be optimal for every type of application.

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

A misconfiguration in the main urls.py file of a Django project is causing issues with processing get requests

In my current Django project, I have a simple CMS where users input a 12-digit Chuckee Cheese membership card number. The requirement is to redact the first 8 digits and display the remaining 4 to the user on the main landing page with blog post content. ...

Python web framework Django, RESTful API implementation, cloud computing platform Microsoft Azure, online platform, cloud-based server

I have successfully developed a website and REST API using Django and Django REST Framework. After testing them on my local machine, my next goal is to deploy them on a remote server. I have chosen to use Microsoft Azure for this purpose. So far, I have s ...

CSS - Achieving full width on hover even when the element has a specified width setting

I am encountering an issue with my CSS. Although I have successfully centered everything, I am facing a problem with the hover effect in CSS. Whenever I apply the active class or hover over an li element, the background color expands to 100%. Additionally, ...

Setting the default selection in AngularJS based on the URL entered

I've encountered an issue with a dropdown menu in my AngularJS version 1.4 application. The dropdown menu contains links to different sections of the page. The problem arises when I directly enter the page URL - instead of selecting the correct link f ...

I'm encountering a Type Error message in VS Code terminal stating that converting data to string is not a function. Can someone please help me understand this type error? I am new to Node.js and

const fileSystem = require('fs'); const data = fileSystem.readFileSync('example.txt'); if (data) console.log(data.toString()); console.log('Program Ended'); This is the code I wrote: and this is the error message my terminal ...

What is the method to retrieve results using 'return' from NeDB in vue.js?

Seeking assistance on retrieving data from NeDB within a method in a .vue file using electron-vue. Currently, I am aware that the data can be stored in a variable, but my preference is to fetch it using 'return' as I intend to utilize the result ...

Tips for quietly printing a PDF document in reactjs?

const pdfURL = "anotherurl.com/document.pdf"; const handleDirectPrint = (e: React.FormEvent) => { e.preventDefault(); const newWin: Window | null = window.open(pdfURL); if (newWin) { newWin.onload = () => ...

Experiencing a specific error when utilizing the <v-file-input> component

I've integrated VueJS with vuetify. When I switch from an input tag to a v-file-input component, I encounter an error when triggering the function @click. Below is the script and template code: <script> import papa from "papaparse"; export ...

Having trouble parsing a JSON object using the fetch method in React while trying to retrieve data from my database

While using fetch with the "get" method, I encountered an issue where passing the response from my SQL database to my object using useState results in an empty object. However, when I print the response data from my database through console logs, it shows ...

Issue with socket malfunctioning when integrated with express

I’m encountering an issue with the socket in my program. While I can easily broadcast from any part of the program using "io" connection, I face limitations when trying to use "socket" for broadcasting unless it is within the same connection as "io." I a ...

Implementing data updates in Ruby on Rails through AJAX or jQuery

Within a text field input lies the value of a database attribute (ref). Upon focusing on the field, a border appears and disappears upon clicking out. My dilemma is that I wish for the data within the text field to be saved in the database without the nee ...

Angular 8 and the conundrum of date parsing issues

const timestamp = '2020-07-11T00:05:00'; const dateOfFlight = new Date(timestamp); dateOfFlight.getMonth() // The output should be 6 However, it is expected to be 7 based on the provided timestamp. ...

How to create a sequence of queries to a mongoDB database (using mongoose) depending on a condition

Source Code let placeForSearch="hampi" let filteredHotelFacilities=req.body.filter //["Free Wifi"] let hotels = await Hotel.find({placeForSearch}) .where("facilities") .select(selectedProperties) .skip(pageNu ...

Clicking on the button will result in the addition of new

Having some trouble with jQuery as I try to dynamically add and remove HTML elements (on click of +) while also making sure each element has a unique name and ID like "name_1", "name_2"... Unfortunately, things aren't quite going as planned. Below i ...

Create a new division directly underneath the bootstrap column

Imagine having a bootstrap table like this: https://i.sstatic.net/kXHiP.jpg Now, if you want to click on a column and open a div with more details below it, is it achievable with CSS or JavaScript? https://i.sstatic.net/HIfkK.jpg I tried using the Metr ...

Troubleshooting: Bootstrap 5.0 Navbar Dropdown Issue Unresolved

My navbar dropdown isn't working when clicked. I've searched for solutions without success. Is there a script missing? layout.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> ...

Modify the text on a button using vanilla JavaScript

Although it may seem like a simple question, I am struggling to change the text on my button. The code for my button in the web browser console is: <button class="nav-link active" id="coholder-tab" data-toggle="tab" data-t ...

Is there a way to seamlessly update button values in VueJs from an api request without needing to reload the page or manually clicking something? Or perhaps there is an alternative method to achieve this?

I attempted to solve the issue by implementing while(true) within the created method so that it constantly updates by sending frequent requests to Flask. Is there a different approach to updating my value? Vue: let app = Vue.createApp({ data ...

Guide on creating a function that accepts an Array of strings as a parameter and displays the initial letter of each element individually on separate lines

I am currently tackling my initial JavaScript assignment which involves the task of creating a function that accepts an array of strings as its parameter and outputs the first letter of each element individually on separate lines. The unique requirement ...

I'm facing some uncertainties with a couple of AngularJS code snippets

At my workplace, I am tasked with making modifications to an angularjs project. However, I find the code quite complex and challenging to fully comprehend: app.controller("complementsController", function($scope, $rootScope, $mdSidenav, $timeout, $localSt ...