How to call an external JavaScript function in a Django template

In this tutorial, we will learn how to call an external javascript function in a Django template.

Steps to perform this task:-

  1. Create Project
  2. Start an app
  3. Create an HTML file
  4. Create a javascript file
  5. Call the function

Create Project:-

To start the project open command prompt and type django-admin startproject mysitethis will create a project in your current working directory.

Start an app:-

We need to start an app in our current working directory that is mysite. To start an app we have to type python manage.py runserverin your terminal.

Create an HTML file:-

To create an HTML file first we need to create a folder named templates and on the folder template we will create an HTML file named index.html and type the below code on the file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML PAGE</title>
</head>
<body>
    I love CodeSpeedy
</body>
</html>

After doing this, we need to define the templates folder in settings.py.

Open settings.py and search for the TEMPLATES in this there is DIRS on that just type ‘templates’ this will define the folder.

To view the index.html file open views.py and type:-

from django.shortcuts import render

# Create your views here.
def home(request):
    return render(request,'index.html')

Create a JavaScript file:-

To do so just create a folder named statics in your project and inside the folder create a javascript file named as app.js.

Open settings.py and below the STATIC_URL just add STATICFILES_DIRS = [
os.path.join(BASE_DIR,'statics')
]
just to tell which folder we have to call.

Call the JavaScript function

To call the function open index.html and in the head just type the below code

{%load staticfiles%}
    <script src="{%% static 'app.js'}"></script>

This will call the javascript function in our index.html file.

I hope you like this tutorial.

Happy Coding!

Leave a Reply

Your email address will not be published.