Executing JavaScript functions within static files in Django

I can't figure out why I'm unable to invoke a javascript function when clicking my Bootstrap button in a Django project.

In my directory, I have set up the static folder as "main/static/main/js/script.js". While I can successfully load the static CSS file for Bootstrap without any problems, the javascript function "testing()" isn't getting called for some reason. The web browser console shows an error message saying "Uncaught ReferenceError: testing is not defined onclick." Is AJAX necessary in this scenario, or could there be an issue with my settings or URL path?

EDIT: I also noticed that my static CSS isn't working properly either. When I applied simple CSS styling changes, they weren't reflected unless I used inline styling instead.

This is a snippet from my settings.py file:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'main.apps.MainConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]



# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATICFILES_DIRS = [BASE_DIR /'main/static']
STATIC_URL = '/static/'

Here is the contents of my scripts.js file:

function testing() {
  alert("Button clicked!");
}

Below is a section from my index.html file which utilizes Bootstrap:

{%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" />
    <meta name="description" content="" />
    <meta name="author" content="" />
    <title>MoviePicks</title>
    <!-- Core theme CSS (includes Bootstrap)-->
    <link rel="icon" type="image/x-icon" href="{%static 'main/assets/favicon.ico'%}" />
    <link href="{%static 'main/css/styles.css'%}" rel="stylesheet" />
  </head>
  <body id="page-top">
    <!-- Header-->
    <header class="bg-dark bg-gradient text-white">
      <div class="container px-4 d-flex flex-column align-items-center text-center">
        <!--code to play lottie animation file-->
        <lottie-player
          src="https://lottie.host/de506df5-436d-4157-9721-8cc927339ca6/BtifhCSc5e.json"
          background="transparent"
          speed="1"
          style="width: 200px; height: 200px"
          loop
          autoplay
        ></lottie-player>
        <!--____________________________________-->
        <button
          id="mainbtn"
          onclick="testing()"
          type="button"
          class="btn btn-danger"
          style="
            --bs-btn-padding-y: 0.3rem;
            --bs-btn-padding-x: 1.5rem;
            --bs-btn-font-size: 1.75rem;
          "
        >
          Go!
        </button>
      </div>
    </header>
    <!-- Bootstrap core JS-->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
    <script src="{%static 'main/js/scripts.js'%}"></script>
  </body>
</html>

Please disregard any missing closing tags as I've condensed the HTML code for brevity.

Answer №1

STATICFILES_DIRS = [BASE_DIR /'main/static']

Please confirm that a comma is not missing in the code, right?

STATICFILES_DIRS = [BASE_DIR ,'main/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

Perform an action when a key is held down and when it is released

I am looking to implement a function that needs to be called under certain conditions: It should be triggered every second while a key is being held down (for example, if the key is held down for five seconds, it should fire 5 times every second). If ...

Cricket score update features on the client side

Looking for assistance with client-side code development! I am currently working on an Android application using Ionic that involves live cricket scores. I have purchased a cricket API and understand how to connect to it using Node.js on the server side. ...

I'm curious about the correct method for updating a parent component using a shared service within the ngOnInit function in Angular version 13

There have been instances where I encountered a scenario multiple times, where I utilize a shared service within the ngOnInit of a component to update a value in another component, specifically its parent. This often leads to the well-known Error: NG0100: ...

The responsiveness of Angular Material appears to be limited when tested in Chrome's debug mode for different devices

I have come across a peculiar issue. Within my HTML file, I have defined two attributes: Hide me on small devices Hide me on larger than small devices When I resize the window, the attributes work as intended. However, when I enter device debug mode ( ...

Can someone explain why my button icons are not aligning to the center properly?

I have a small issue with the icons I pulled from react-icons - they appear slightly raised within the buttons. How can I position them in the middle? That's my only query, but I can't post it alone due to mostly having code in my post. What an ...

Error encountered with NodeJS Express Module: TypeError - Unable to access property 'finished' as it is undefined

Recently, I've been working on creating an API that can extract text from a website based on specific keywords. To achieve this, I utilized Selenium to load the site and retrieve the text. However, I encountered an issue with sending the extracted tex ...

Getting the value of "Page=?" from the href attribute in an HTML tag can be done using Selenium Webdriver and Java

I am looking to extract the value "page = ?" from a specific "href" tag in the HTML code below. I need this value for my Selenium WebDriver script so that my loop can iterate up to page 53. Can someone guide me on how to retrieve the "page =" value mentio ...

Determining the local coordinate system of an object in THREE.js

I'm a beginner in Three.js and could use some guidance... I've been moving and rotating an object randomly multiple times. Eventually, I need to determine the orientation of the local coordinate system of that object for physics calculations... ...

Are there alternative methods for retrieving data in Vue Hacker News besides using prefetching?

I am currently developing a Vue single page application with server side rendering using Vue SSR. As per the official documentation, data in components will be prefetched server-side and stored in a Vuex store. This process seems quite intricate. Hence, ...

Looking to create circular text using HTML, CSS, or JavaScript?

https://i.sstatic.net/pnu0R.png Is there a way to generate curved text in HTML5, CSS3, or JavaScript similar to the image linked above? I've experimented with transform: rotate(45deg); but that just rotates the text without curving it. Additionally, ...

Refresh your jQuery function without the need to reload the entire page

Is there a way to update a function's parameters without reloading the entire page? For instance, if I modify the 'style' dropdown value as shown in the URL image, can it be passed to the accordion function so that the accordion's color ...

Facing some unexpected issues with integrating Django and AngularJS, unclear on the cause

In my simple Angular application, I encountered an issue. When I run the HTML file on its own in the browser, the variable name "nothing" is displayed as expected. However, once I integrate the app into Django by creating a dummy view that simply calls a t ...

"Sparkling div animation with the use of jQuery's .hover() function

<script> $(document).ready(function () { $("#logo_").hide(); $("#logo_learn").hide(); }) function sl() { $("#logo_learn").slideToggle(500); $("#logo_").fadeIn(); } function hl() { $("#logo_learn").slideToggle(500); $("#logo_ ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

What is the best way to modify a CSS property using logical operators in JQuery?

If an element with the class ".has_padding" does not have any text content, it should be set to "display:none;". However, those elements with text inside should remain visible. Below is some code where I have styled the elements to demonstrate the issue. ...

Tips on Creating a Display None Row with a Sliding Down Animation Using Javascript

I am working with a table that has some hidden rows which only appear when the "show" button is clicked. I want to know how I can make these hidden rows slide down with an effect. Here's the snippet of my code: function toggleRow(e){ ...

Combine several objects into one consolidated object

Is there a way to combine multiple Json objects into one single object? When parsing an array from AJAX, I noticed that it logs like this: 0:{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support", ...} 1:{id: "25", user: "Jim ...

Having trouble with NPM Moment.js in React: Why is moment__WEBPACK_IMPORTED_MODULE_2__format not functioning properly?

scenario, After resolving my current issue using dateFns (date-fns.org), I am interested in integrating Momentjs into the project as well. The task at hand involves converting data to a string format within an app built with create-react-app. However, wh ...

List of JavaScript arrays with indices

Today I was experimenting with regex in JavaScript and stumbled upon a unique data structure that I had never encountered before: an array with some entries having keys. One method that returns such a data structure is the regex match function. Let's ...

What is preventing me from updating the value of a variable in this manner?

Trying to understand the reason behind an issue with overwriting a value passed to an angularJS directive using an isolate scope (@). When attempting to change the value of vm.index with the following: vm.index = parseInt(vm.index, 10) It does not seem t ...