I am experiencing difficulty in loading JS files within a Django template

I am encountering an issue with my Django project. While my static files for images and CSS are loading correctly, the JavaScript files are not. I have created a folder named "static" within my app with the following structure: static/js/my_app/, where my JavaScript files are stored.

Below is the section of my template that includes JavaScript scripts:

<!-- Scripts -->
<script src="{% static 'js/landing/jquery.min.js' %}"></script>
<script src="{% static 'js/landing/jquery.scrolly.min.js' %}"></script>
<script src="{% static 'js/landing/jquery.dropotron.min.js' %}"></script>
<script src="{% static 'js/landing/jquery.scrollex.min.js' %}"></script>
<script src="{% static 'js/landing/util.js' %}"></script>
<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
<script src="{% static 'js/landing/main.js' %}"></script>

Here is the relevant part of my settings.py file related to static files:

STATIC_URL = '/static/'

STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

Any assistance would be appreciated. Thank you!

Answer №1

It's typically recommended to organize your files in the following manner: app_name/static/app_name/js/file.js

To reference the file in your template, you can simply use: {% static 'app_name/js/file_name.js' %}, assuming that your static setup is correct.

However, it appears that in your configuration, you have placed the file under static/js/app_name instead of static/app_name/js.

Answer №2

To easily call your JavaScript or CSS file /static/css/a.css in your template, follow these steps:

import os
def root(x):
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), '..',x)
MEDIA_ROOT = root('media')
MEDIA_URL = '/media/'
STATIC_ROOT = root('staticstorage')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    root('static'),
)
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'dajaxice.finders.DajaxiceFinder',
)
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    'django.template.loaders.eggs.Loader',

)
TEMPLATE_DIRS = (
    root('templates')
)
TEMPLATE_CONTEXT_PROCESSORS = (

    "--------------------------------------"
    'django.core.context_processors.media',
    'django.core.context_processors.static',
)

url.py

from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.conf.urls.static import static
admin.autodiscover()

urlpatterns = patterns('',
)

urlpatterns += patterns('',
    url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_ROOT, 'show_indexes': False}),
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),

) 

urlpatterns += staticfiles_urlpatterns()

Answer №3

Although unconventional, following these steps might yield positive results: Within the existing js directory, create a new subdirectory named js and move your file into it. Refresh your site to see if any changes have occurred. Next, create another file within the newly created js directory and transfer your file into it. Save your work again and run it once more. This will result in your file being located at js/js/js/file.js. Return the file to its original directory and test the code again to check for any improvements. Despite its unorthodox nature, this method has proven effective. Remember to update the HTML file with the correct path each time you move the JavaScript file. While calculations were made from the js file, ensure to perform calculations from the actual file containing your JavaScript code.

Answer №4

The issue may be related to the website's cache, trying to refresh the page by pressing ctrl+f5 could resolve it

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

What is the best way to transfer a variable from a Node.js Express server to an EJS HTML file in order to toggle alert visibility?

Hello, I am currently facing a challenge in sending a variable from my app.js file to my ejs HTML file in order to toggle the display of an alert. Here is what the relevant part of my app.js code looks like: view image description here Initially, I attem ...

Leveraging Gatsbyjs to Integrate GraphQL Data with Material UI Library

Just starting out as a Frontend Developer and currently learning Gatsbyjs along with the Material UI library. I'm working on creating a new page using the Material UI Gatsby Starter code available here. However, I've encountered an issue when tr ...

MUI options - The specified type 'string' cannot be matched with type '"icon" | "iconOnly" | "text" | "outlined" | "contained" | undefined'

Is it possible to utilize custom variants in MUI v5? I am having trouble using a custom variant according to their documentation: https://mui.com/material-ui/customization/theme-components/#creating-new-component-variants declare module "@mui/material ...

Managing the response from a variable returned by jQuery's .load method

I am facing an issue with my code. I am using jQuery post to validate whether the name of the filter is available for use. $.post('check-username.php', $("#myform").serialize(), function(data) { alert(data); }); When I use the alert to disp ...

How can you make sure that mouse events pass through the KineticJS stage?

Is it possible to have a PanoJS3 component covering the entire screen with a KineticJS stage on top, but still allow touch events to pass through the KineticJS stage to what lies beneath? I want shapes on the stage or layer to receive the touch events, wh ...

Creating Browser Extensions with Vue.js and Vue CLI

I am in the process of creating a Chrome Extension with a frontend powered by Vue.js. Everything was going smoothly using vuecli until my app started utilizing the Webextension-API. This API is only accessible to registered Extensions, not normal websites. ...

Converting API data in Angular using rxjs

Hey there, I received this response from an API: { "records":[ { "id":1, "motivazione":"", "autorizzazione":false, } ] } Can anyone help me transform it to loo ...

Encountering Internal Server Error when running Node-Express app on render.com with query parameters live

Currently, I am facing an issue while attempting to execute a live route with query using my nodejs express application on render.com. Strangely, all other routes connected to the crud operations are functioning properly except for the search filter route ...

Issue with resetting the state of a react-select component remains unresolved

I'm currently facing two issues with my react-select component: Firstly, once I select an option, I am unable to change it afterwards. Second, when my form is reset, the react-select component does not reset along with the other fields. For simplici ...

The error message from the mongoose plugin is indicating a problem: it seems that the Schema for the model "Appointment" has not been properly registered

I need help troubleshooting a mongoose error that is being thrown. throw new mongoose.Error.MissingSchemaError(name); ^ MissingSchemaError: Schema hasn't been registered for model "Appointment". Use mongoose.model(name, schema) I have double-c ...

What is the best way to access and iterate through JSON data?

I am trying to extract data from my Json file, however, I cannot use a specific 'key' because it changes on a daily basis. https://i.sstatic.net/sZySk.png My attempted solution is as follows: template: function(params) { const objects ...

Tips for incorporating external libraries into a Grafana data source plugin

What's the best way to integrate an external library into a Grafana datasource plugin? My plugin is functioning properly, but I encounter an error when trying to use the "mqtt" library that I have installed and added to the package.json file: Plugin ...

Concentrate on the HTML element once it becomes active

I am facing a challenge where I need to focus on a specific input element. However, there is a spinner that appears on page load and remains hidden until certain http requests are completed. All inputs are disabled until the requests are finished. The setu ...

react-select is not displaying assets correctly within the react-modal component

I am currently utilizing react-select to implement a select field within a modal created with react-modal. However, I am encountering issues with the assets not displaying correctly, as depicted in this image (the arrow is missing and the list is not showi ...

When transitioning from the accordion format for mobile to the tab layout for desktop, the tab panel displays an inaccurate title despite the content being accurate

Currently, I am working on developing a navigation system. The objective is to have an accordion-like layout for mobile and tab-based layout for desktop. Although I have implemented this setup, there seems to be an issue: For instance, if "Link #2" tab is ...

Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber. dataService.ts fetchFormData(){ return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest ...

What makes django-channels stand out compared to regular python websockets?

Once upon a time, people used python websockets with django for websocket handling. But then along came django-channels, an official django project designed to support websockets in django. Can anyone highlight the benefits of using django channels over tr ...

Fetch initial data, then refresh upon completion (using Django or ajax)

My webpage is loading very slowly because it needs to fetch over 50 objects from the database. I want to optimize this process by initially loading only the first 10 results, allowing the server to fetch the rest in the background, and then refreshing the ...

Clicking on a marker in Google Maps will display the address

I have a map that contains several markers, each designated by their latitude and longitude coordinates. I would like to be able to see the address associated with each marker when I click on it. However, I am currently experiencing an issue where nothing ...

What is the correct way to exclude and remove a portion of the value within an object using TypeScript?

The function useHider was created to conceal specific values from an object with the correct type. For example, using const res = useHider({ id: 1, title: "hi"}, "id"), will result in { title: "hi" } being returned. Attempting ...