Passing A JavaScript Variable In An HTML File To A Django View Function

Hello everyone.

I am trying to pass a JavaScript variable called “facialImageURL” in an HTML file to a Django view function.

The following HTML file called “facial-login.html” is where the “facialImageURL” variable is located:

<!doctype html>

<head>
    <style>
    #video {
        border: 1px solid black;
        width: 320px;
        height: 240px;
    }

    #photo {
        border: 1px solid black;
        width: 320px;
        height: 240px;
    }

    #canvas {
        display: none;
    }

    .camera {
        width: 340px;
        display: inline-block;
    }

    .output {
        width: 340px;
        display: inline-block;
    }

    #startbutton {
        display: block;
        position: relative;
        margin-left: auto;
        margin-right: auto;
        bottom: 36px;
        padding: 5px;
        background-color: #6a67ce;
        border: 1px solid rgba(255, 255, 255, 0.7);
        font-size: 14px;
        color: rgba(255, 255, 255, 1.0);
        cursor: pointer;
    }

    .contentarea {
        font-size: 16px;
        font-family: Arial;
        text-align: center;
    }

    .capture-image {
        position: absolute;
        top: 400px;
        left: 700px;
    }
    </style>
    <!--The title of the HTML document.-->
    <title>Facial Image Recognition</title>
</head>

<body>
    <div class="contentarea">
        <h1>Facial Image Recognition</h1>

        <div class="camera">
            <video id="video">Video stream not available.</video>
        </div>
        <!--An id on a <button> tag assigns an identifier to the button.
            The id allows JavaScript to easily access the <button> element
            and manipulate it.
            When a user clicks on the "Capture Image" button, the -->
        <div class="capture-image">
            <button id="startbutton">Capture Image</button>
        </div>
        
        <!-- <div>
        <a href="{% url 'facial-login-result' %}" id="startButton" 
           class="btn btn-info btn-lg">
           <span class="glyphicon glyphicon-camera"></span>Capture Image
        </a>
        </div> -->

        <!--The HTML canvas tag is where the image frames are stored
            before they are converted into an image of proper format
            to be shown using the <img> tag.-->
        <canvas id="canvas"></canvas>

        <div class="output">
            <img id="photo" alt="The image captured will appear in this box.">
        </div>
    </div>

    <script>

    (function() {

        // We will scale the photo width to this.
        var width = 320;
        // The height will be computed based on the input stream.
        var height = 0;

        var streaming = false;

        var video = null;
        var canvas = null;
        var photo = null;
        var startbutton = null;

        function startup() {
            video = document.getElementById('video');
            canvas = document.getElementById('canvas');
            photo = document.getElementById('photo');

            /*The following line is executed when a user clicks on the
              "Capture Image" button.

              document.getElementById returns the element whose 'id'
              is 'startbutton'.*/
            startbutton = document.getElementById('startbutton');

            // Access the video stream from the webcam.
            navigator.mediaDevices.getUserMedia({
                video: true,
                audio: false
            })
            // Upon success, stream video in a video tag.
            .then(function(stream) {
                video.srcObject = stream;
                video.play();
            })
            .catch(function(err) {
                console.log("An error occurred: " + err);
            });

            video.addEventListener('canplay', function(ev) {
                if (!streaming) {
                    height = video.videoHeight / (video.videoWidth / width);

                    if (isNaN(height)) {
                        height = width / (4 / 3);
                    }

                    video.setAttribute('width', width);
                    video.setAttribute('height', height);
                    canvas.setAttribute('width', width);
                    canvas.setAttribute('height', height);
                    streaming = true;
                }
            }, false);

            startbutton.addEventListener('click', function(ev) {
                takepicture();
                ev.preventDefault();
            }, false);

            clearphoto();
        }

        /*Collect the frames of the photo from the canvas and then
          convert it into a PNG format, so that it can be shown in
          the HTML page.*/
        function clearphoto() {
            var context = canvas.getContext('2d');
            context.fillStyle = "#AAA";
            context.fillRect(0, 0, canvas.width, canvas.height);

            var data = canvas.toDataURL('image/png');

            photo.setAttribute('src', data);
        }

        /*Capture a frame from the video stream.*/
        function takepicture() {
            var context = canvas.getContext('2d');
            if (width && height) {
                canvas.width = width;
                canvas.height = height;

                /*The canvas takes a snapshot of the video.*/
                context.drawImage(video, 0, 0, width, height);

                /*toDataURL('image/png') returns a data URL containing a
                  representation of the image in PNG format.
                  
                  'data' will hold the URL link of each image that is
                  captured from the camera.*/
                var data = canvas.toDataURL('image/png');

                /*'src' is the name of the attribute whose value is to be set.
                  'data' is a string containing the value to assign to the attribute.
                  
                  The data is fed as a source of the image element.*/
                photo.setAttribute('src', data);

                let facialImageURL = '<img src="'+data+'"/>';

                // document.write('<img src="'+data+'"/>');

            } else {
                clearphoto();
            }
        }

        /*The following code will call the startup() function when
          the HTML page is loaded.*/
        window.addEventListener('load', startup, false);
    })();
    </script>
</body>

</html>

Any ideas or suggestions on how this can be done? Thank you.

In general, you have 4 ways to pass data from JavaScript to a Django view.

  • As an element in the URL:

    • e.g. path('/some/url/<str:variable_name>/', ...)
  • As a query variable:

    • e.g. https://example.com/some/url?var=some_url_encoded_data
  • As POST data in a form submission

  • As JSON in a POST

You then need to write the view to accept and use that data in the manner in which it is being supplied.

Never lose sight of the fact that Django is running in the server to render a template and send the rendered HTML to the browser, and the JavaScript is running in the browser after it has been rendered by the server and sent to that browser. That’s two separate locations at two separate points in time.

2 Likes

And how would we catch this in Django? Is it in the request object or?

Correct. See Request and response objects | Django documentation | Django

1 Like

So something like
Myvar = QueryDict(‘var’)
In the view?

More like myvar = request.GET['var']

1 Like

But in the view function, right?

Yes, wherever you need to use it.

1 Like

Dear Mr. Whitesell and all others:

I have added the following code inside the facial-login.html file in an effort to send the JavaScript variable ‘data’ to the server as a POST request:
var URL = “{% url ‘facial-login-result’ %}”;

HTML Portion

<button class="sendButton" id="sendButton">Submit Facial Image</button>

JavaScript Portion

    /*POST the data (the facial image) to the server via AJAX.*/
    function SendFacialImage(){
        var facialImage = {'data': data};
        $.post(URL, facialImage, function(response){
            if(response === 'success')
            { 
                alert('Facial Image Successfully Sent!'); 
            }
            else{ 
                alert('Error Sending Facial Image!'); 
            }
        });
    }

    $(document).ready(function(){
        $('#sendButton').click(function(){
            SendFacialImage();
        });
    });

The following is the entire facial-login.html file:

<!DOCTYPE html>
<html>

<head>
    <style>
    #video {
        border: 1px solid black;
        width: 500px;
        height: 500px;
    }

    #photo {
        border: 1px solid black;
        width: 500px;
        height: 500px;
    }

    #canvas {
        display: none;
    }

    .camera {
        width: 500px;
        display: inline-block;
    }

    .output {
        width: 500px;
        display: inline-block;
    }

    #startbutton {
        display: block;
        position: relative;
        margin-left: auto;
        margin-right: auto;
        bottom: 36px;
        padding: 5px;
        background-color: #6a67ce;
        border: 1px solid rgba(255, 255, 255, 0.7);
        font-size: 14px;
        color: rgba(255, 255, 255, 1.0);
        cursor: pointer;
    }

    .contentarea {
        font-size: 16px;
        font-family: Arial;
        text-align: center;
    }

    /* .sendButton {
        background-color: #4CAF50;
        border: none;
        color: white;
        padding: 20px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
        border-radius: 12px;
    } */

    .sendButton {
        position: absolute;
        top: 327px;
        text-align: center;
    }

    </style>
    <!--The title of the HTML document.-->
    <title>Facial Image Recognition</title>
</head>

<body>
    <div class="contentarea">
        <h1 align="center">Facial Image Recognition</h1>

        <div class="camera">
            <video id="video">Video stream not available.</video>
        </div>

        <!--An id on a <button> tag assigns an identifier to the button.
            The id allows JavaScript to easily access the <button> element
            and manipulate it.-->
        <button id="startbutton">Capture Image</button>

        <!--The following button will trigger the JavaScript function.-->
        <!-- <button class="sendButton">Submit Facial Image</button> -->
        <button class="sendButton" id="sendButton">Submit Facial Image</button>

        <!--The HTML canvas tag is where the image frames are stored
            before they are converted into an image of proper format
            to be shown using the <img> tag.-->
        <canvas id="canvas"></canvas>

        <div class="output">
            <img id="photo" alt="The image captured will appear in this box.">
        </div>
    </div>

    <script>
    var data;

    (function() {

        // We will scale the photo width to this.
        var width = 500;
        // The height will be computed based on the input stream.
        var height = 0;

        var streaming = false;

        var video = null;
        var canvas = null;
        var photo = null;
        var startbutton = null;

        function startup() {
            video = document.getElementById('video');
            canvas = document.getElementById('canvas');
            photo = document.getElementById('photo');

            /*The following line is executed when a user clicks on the
              "Capture Image" button.

              document.getElementById returns the element whose 'id'
              is 'startbutton'.*/
            startbutton = document.getElementById('startbutton');

            // Access the video stream from the webcam.
            navigator.mediaDevices.getUserMedia({
                video: true,
                audio: false
            })
            // Upon success, stream video in a video tag.
            .then(function(stream) {
                video.srcObject = stream;
                video.play();
            })
            .catch(function(err) {
                console.log("An error occurred: " + err);
            });

            video.addEventListener('canplay', function(ev) {
                if (!streaming) {
                    height = video.videoHeight / (video.videoWidth / width);

                    if (isNaN(height)) {
                        height = width / (4 / 3);
                    }

                    video.setAttribute('width', width);
                    video.setAttribute('height', height);
                    canvas.setAttribute('width', width);
                    canvas.setAttribute('height', height);
                    streaming = true;
                }
            }, false);

            startbutton.addEventListener('click', function(ev) {
                takepicture();
                ev.preventDefault();
            }, false);

            clearphoto();
        }

        /*Collect the frames of the photo from the canvas and then
          convert it into a PNG format, so that it can be shown in
          the HTML page.*/
        function clearphoto() {
            var context = canvas.getContext('2d');
            context.fillStyle = "#AAA";
            context.fillRect(0, 0, canvas.width, canvas.height);

            var data = canvas.toDataURL('image/png');

            photo.setAttribute('src', data);
        }

        /*Capture a frame from the video stream.*/
        function takepicture() {
            var context = canvas.getContext('2d');
            if (width && height) {
                canvas.width = width;
                canvas.height = height;

                /*The canvas takes a snapshot of the video.*/
                context.drawImage(video, 0, 0, width, height);

                /*toDataURL('image/png') returns a data URL containing a
                  representation of the image in PNG format.
                  
                  'data' will hold the URL link of each image that is
                  captured from the camera.*/
                data = canvas.toDataURL('image/png');

                /*'src' is the name of the attribute whose value is to be set.
                  'data' is a string containing the value to assign to the attribute.
                  
                  The data is fed as a source of the image element.*/
                photo.setAttribute('src', data);

                let facialImageURL = '<img src="'+data+'"/>';

                // document.write('<img src="'+data+'"/>');

            }else {
                clearphoto();
            }
        }

        /*The following code will call the startup() function when
          the HTML page is loaded.*/
        window.addEventListener('load', startup, false);
    })();

    var URL = "{% url 'facial-login-result' %}";

    /*POST the data (the facial image) to the server via AJAX.*/
    function SendFacialImage(){
        var facialImage = {'data': data};
        $.post(URL, facialImage, function(response){
            if(response === 'success')
            { 
                alert('Facial Image Successfully Sent!'); 
            }
            else{ 
                alert('Error Sending Facial Image!'); 
            }
        });
    }

    $(document).ready(function(){
        $('#sendButton').click(function(){
            SendFacialImage();
        });
    });
    </script>
</body>

</html>

The following is what I have added to the view function FacialLoginResult(request):

def FacialLoginResult(request):
    if request.method == 'POST':
        if 'data' in request.POST:
            facialImage = request.POST['data']

            context = {
                'facialImage': facialImage,
            }

            return render(request, 'users/facial-login-result.html', context)
    else:
        return HttpResponse('Error! Facial Image Not Received.')

Unfortunately, nothing happens when I click on the button with the id “sendButton” titled ‘Submit Facial Image’. Why is this the case? Please let me know. Thanks!

You say “nothing happens” - does that mean it doesn’t generate the POST request to the server?

Since this is a process being initiated by the browser, start with using your browser’s developer tools to see what’s happening. Set breakpoints within the code to examine variables at key locations. Use some debugging statements to display when areas of code are being run.

Debugging is a matter of following what’s going on, and comparing that information to what you think should be happening - and resolving those differences.

Hello Mr. Whitesell.

After clicking the “Submit Facial Image” button, the following image shows what happens in the console:
forbidden

I am receiving a 403 (Forbidden) error which means that the server is refusing to authorise the request. Why is this the case?

This is inside the “Users” application of the Django project.

The following is the Users → facial-login.html file where the button was created:

{% load static %}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<style>
#video {
    border: 1px solid black;
    width: 500px;
    height: 500px;
    object-fit: cover;
}

#photo {
    border: 1px solid black;
    width: 500px;
    height: 500px;
    /*'cover' was set to 'object-fit' here because before this
        the output image would be more vertically stretched than
        the input image.*/
    object-fit: cover;
}

#canvas {
    display: none;
}

.camera {
    width: 500px;
    display: inline-block;
}

.output {
    width: 500px;
    display: inline-block;
}

#startbutton {
    display: block;
    position: relative;
    margin-left: auto;
    margin-right: auto;
    bottom: 36px;
    padding: 5px;
    background-color: #6a67ce;
    border: 1px solid rgba(255, 255, 255, 0.7);
    font-size: 14px;
    color: rgba(255, 255, 255, 1.0);
    cursor: pointer;
}

/************/
#sendButton {
    display: block;
    position: relative;
    margin-left: auto;
    margin-right: auto;
    bottom: 36px;
    padding: 5px;
    background-color: #6a67ce;
    border: 1px solid rgba(255, 255, 255, 0.7);
    font-size: 14px;
    color: rgba(255, 255, 255, 1.0);
    cursor: pointer;
}
/************/

.contentarea {
    position: relative;
    font-size: 16px;
    font-family: Arial;
    text-align: center;
}
</style>

    <!--The title of the HTML document.-->
    <title>Facial Image Recognition</title>

    <link rel="stylesheet" href="{% static 'styles/facial-login.css' %}" type="text/css"/>
</head>
<body>
    <div>
        <video autoplay muted loop id="facialVideoBackground">
            <source src="{% static 'video-backgrounds/kapadokya.mp4' %}" type="video/mp4">
        </video>
    </div>

    <div class="contentarea">
        <h1 align="center">Facial Image Recognition</h1>

        <div class="camera">
            <video id="video">Video stream not available.</video>
        </div>

        <!--An id on a <button> tag assigns an identifier to the button.
            The id allows JavaScript to easily access the <button> element
            and manipulate it.-->
        <button id="startbutton">Capture Image</button>

        <!--The HTML canvas tag is where the image frames are stored
            before they are converted into an image of proper format
            to be shown using the <img> tag.-->
        <canvas id="canvas"></canvas>

        <div class="output">
            <img id="photo" alt="The image captured will appear in this box.">
        </div>

        <!--The following button will trigger the JavaScript function.-->
        <button id="sendButton">Submit Facial Image</button>
    </div>

    <script>
    var data;

    (function() {

        // We will scale the photo width to this.
        var width = 500;
        // The height will be computed based on the input stream.
        var height = 0;

        var streaming = false;

        var video = null;
        var canvas = null;
        var photo = null;
        var startbutton = null;

        function startup() {
            video = document.getElementById('video');
            canvas = document.getElementById('canvas');
            photo = document.getElementById('photo');

            /*The following line is executed when a user clicks on the
              "Capture Image" button.

              document.getElementById returns the element whose 'id'
              is 'startbutton'.*/
            startbutton = document.getElementById('startbutton');

            // Access the video stream from the webcam.
            navigator.mediaDevices.getUserMedia({
                video: true,
                audio: false
            })
            // Upon success, stream video in a video tag.
            .then(function(stream) {
                video.srcObject = stream;
                video.play();
            })
            .catch(function(err) {
                console.log("An error occurred: " + err);
            });

            video.addEventListener('canplay', function(ev) {
                if (!streaming) {
                    height = video.videoHeight / (video.videoWidth / width);

                    if (isNaN(height)) {
                        height = width / (4 / 3);
                    }

                    video.setAttribute('width', width);
                    video.setAttribute('height', height);
                    canvas.setAttribute('width', width);
                    canvas.setAttribute('height', height);
                    streaming = true;
                }
            }, false);

            startbutton.addEventListener('click', function(ev) {
                takepicture();
                ev.preventDefault();
            }, false);

            clearphoto();
        }

        /*Collect the frames of the photo from the canvas and then
          convert it into a PNG format, so that it can be shown in
          the HTML page.*/
        function clearphoto() {
            var context = canvas.getContext('2d');
            context.fillStyle = "#AAA";
            context.fillRect(0, 0, canvas.width, canvas.height);

            var data = canvas.toDataURL('image/png');

            photo.setAttribute('src', data);
        }

        /*Capture a frame from the video stream.*/
        function takepicture() {
            var context = canvas.getContext('2d');
            if (width && height) {
                canvas.width = width;
                canvas.height = height;

                /*The canvas takes a snapshot of the video.*/
                context.drawImage(video, 0, 0, width, height);

                /*toDataURL('image/png') returns a data URL containing a
                  representation of the image in PNG format.
                  
                  'data' will hold the URL link of each image that is
                  captured from the camera.*/
                data = canvas.toDataURL('image/png');

                /*'src' is the name of the attribute whose value is to be set.
                  'data' is a string containing the value to assign to the attribute.
                  
                  The data is fed as a source of the image element.*/
                photo.setAttribute('src', data);

                let facialImageURL = '<img src="'+data+'"/>';

                // document.write('<img src="'+data+'"/>');

            }else {
                clearphoto();
            }
        }

        /*The following code will call the startup() function when
          the HTML page is loaded.*/
        window.addEventListener('load', startup, false);
    })();

    var URL = "{% url 'facial-login-result' %}";

    /*POST the data (the facial image) to the server via AJAX.*/
    function SendFacialImage(){
        var facialImage = {'data': data};
        $.post(URL, facialImage, function(response){
            if(response === 'success')
            { 
                alert('Facial Image Successfully Sent!'); 
            }
            else{ 
                alert('Error Sending Facial Image!'); 
            }
        });
    }

    /*A page can't be manipulated safely until the document is "ready." 
      jQuery detects this state of readiness for you. Code included inside 
      $( document ).ready() will only run once the page Document Object Model
      (DOM) is ready for JavaScript code to execute.*/
    $(document).ready(function(){
        $('#sendButton').click(function(){
            SendFacialImage();
        });
    });
    </script>
</body>

</html>

Inside the Users → views.py file, exists the following function (this is the function that I want to pass the image to):

def FacialLoginResult(request):
    if request.method == 'POST':
        if 'data' in request.POST:
            facialImage = request.POST['data']

            context = {
                'facialImage': facialImage,
            }

            return render(request, 'users/facial-login-result.html', context)
    else:
        return HttpResponse('Error! Facial Image Not Received.')

Time to keep digging.

What are you seeing in your server console where you’re running the application?

Do you have DEBUG=True?

Are you logging requests? If so, check your logs.

Add CSRF token to your data or submit through a FORM

data : {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value},
<form method="POST" action="" id="form">
    {% csrf_token %}
    ...

Cross Site Request Forgery protection

The following is how I am attempting to submit the JavaScript variable ‘data’ to the view function titled ‘AnalyzeFacialImage’:

<form method="POST" action="{% url 'analyze-facial-image' %}">
        {% csrf_token %}
            <h1 align="center">Facial Image Recognition</h1>

            <div class="camera">
                <video id="video">Video stream not available.</video>
            </div>

            <!--An id on a <button> tag assigns an identifier to the button.
                The id allows JavaScript to easily access the <button> element
                and manipulate it.-->
            <button id="startbutton">Capture Image</button>

            <!--The HTML canvas tag is where the image frames are stored
                before they are converted into an image of proper format
                to be shown using the <img> tag.-->
            <canvas id="canvas"></canvas>

            <div class="output">
                <img id="photo" alt="The image captured will appear in this box.">
            </div>

            <!--The following button will trigger the JavaScript function.-->
            <button id="sendButton">Submit Facial Image</button>
        </form>

The following is inside the urls.py file:

path('analyze-facial-image/', user_views.AnalyzeFacialImage, name='analyze-facial-image'),

The following is the entire facial-login.html file where the JavaScript variable ‘data’ is originally:

{% load static %}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<style>
#video {
    border: 1px solid black;
    width: 500px;
    height: 500px;
    object-fit: cover;
}

#photo {
    border: 1px solid black;
    width: 500px;
    height: 500px;
    /*'cover' was set to 'object-fit' here because before this
        the output image would be more vertically stretched than
        the input image.*/
    object-fit: cover;
}

#canvas {
    display: none;
}

.camera {
    width: 500px;
    display: inline-block;
}

.output {
    width: 500px;
    display: inline-block;
}

#startbutton {
    display: block;
    position: relative;
    margin-left: auto;
    margin-right: auto;
    bottom: 36px;
    padding: 5px;
    background-color: #6a67ce;
    border: 1px solid rgba(255, 255, 255, 0.7);
    font-size: 14px;
    color: rgba(255, 255, 255, 1.0);
    cursor: pointer;
}

/************/
#sendButton {
    display: block;
    position: relative;
    margin-left: auto;
    margin-right: auto;
    bottom: 36px;
    padding: 5px;
    background-color: #6a67ce;
    border: 1px solid rgba(255, 255, 255, 0.7);
    font-size: 14px;
    color: rgba(255, 255, 255, 1.0);
    cursor: pointer;
}
/************/

.contentarea {
    position: relative;
    font-size: 16px;
    font-family: Arial;
    text-align: center;
}
</style>

    <!--The title of the HTML document.-->
    <title>Facial Image Recognition</title>

    <link rel="stylesheet" href="{% static 'styles/facial-login.css' %}" type="text/css"/>
</head>
<body>
    <div>
        <video autoplay muted loop id="facialVideoBackground">
            <source src="{% static 'video-backgrounds/kapadokya.mp4' %}" type="video/mp4">
        </video>
    </div>

    <div class="contentarea">
        <form method="POST" action="{% url 'analyze-facial-image' %}">
        {% csrf_token %}
            <h1 align="center">Facial Image Recognition</h1>

            <div class="camera">
                <video id="video">Video stream not available.</video>
            </div>

            <!--An id on a <button> tag assigns an identifier to the button.
                The id allows JavaScript to easily access the <button> element
                and manipulate it.-->
            <button id="startbutton">Capture Image</button>

            <!--The HTML canvas tag is where the image frames are stored
                before they are converted into an image of proper format
                to be shown using the <img> tag.-->
            <canvas id="canvas"></canvas>

            <div class="output">
                <img id="photo" alt="The image captured will appear in this box.">
            </div>

            <!--The following button will trigger the JavaScript function.-->
            <button id="sendButton">Submit Facial Image</button>
        </form>
    </div>

    <script>
    var data;

    (function() {

        // We will scale the photo width to this.
        var width = 500;
        // The height will be computed based on the input stream.
        var height = 0;

        var streaming = false;

        var video = null;
        var canvas = null;
        var photo = null;
        var startbutton = null;

        function startup() {
            video = document.getElementById('video');
            canvas = document.getElementById('canvas');
            photo = document.getElementById('photo');

            /*The following line is executed when a user clicks on the
              "Capture Image" button.

              document.getElementById returns the element whose 'id'
              is 'startbutton'.*/
            startbutton = document.getElementById('startbutton');

            // Access the video stream from the webcam.
            navigator.mediaDevices.getUserMedia({
                video: true,
                audio: false
            })
            // Upon success, stream video in a video tag.
            .then(function(stream) {
                video.srcObject = stream;
                video.play();
            })
            .catch(function(err) {
                console.log("An error occurred: " + err);
            });

            video.addEventListener('canplay', function(ev) {
                if (!streaming) {
                    height = video.videoHeight / (video.videoWidth / width);

                    if (isNaN(height)) {
                        height = width / (4 / 3);
                    }

                    video.setAttribute('width', width);
                    video.setAttribute('height', height);
                    canvas.setAttribute('width', width);
                    canvas.setAttribute('height', height);
                    streaming = true;
                }
            }, false);

            startbutton.addEventListener('click', function(ev) {
                takepicture();
                ev.preventDefault();
            }, false);

            clearphoto();
        }

        /*Collect the frames of the photo from the canvas and then
          convert it into a PNG format, so that it can be shown in
          the HTML page.*/
        function clearphoto() {
            var context = canvas.getContext('2d');
            context.fillStyle = "#AAA";
            context.fillRect(0, 0, canvas.width, canvas.height);

            var data = canvas.toDataURL('image/png');

            photo.setAttribute('src', data);
        }

        /*Capture a frame from the video stream.*/
        function takepicture() {
            var context = canvas.getContext('2d');
            if (width && height) {
                canvas.width = width;
                canvas.height = height;

                /*The canvas takes a snapshot of the video.*/
                context.drawImage(video, 0, 0, width, height);

                /*toDataURL('image/png') returns a data URL containing a
                  representation of the image in PNG format.
                  
                  'data' will hold the URL link of each image that is
                  captured from the camera.*/
                data = canvas.toDataURL('image/png');

                /*'src' is the name of the attribute whose value is to be set.
                  'data' is a string containing the value to assign to the attribute.
                  
                  The data is fed as a source of the image element.*/
                photo.setAttribute('src', data);

                let facialImageURL = '<img src="'+data+'"/>';

                // document.write('<img src="'+data+'"/>');

            }else {
                clearphoto();
            }
        }

        /*The following code will call the startup() function when
          the HTML page is loaded.*/
        window.addEventListener('load', startup, false);
    })();

    var URL = "{% url 'facial-login-result' %}";

    /*POST the data (the facial image) to the server via AJAX.*/
    function SendFacialImage(){
        var facialImage = {'data': data};
        $.post(URL, facialImage, function(response){
            if(response === 'success')
            { 
                alert('Facial Image Successfully Sent!'); 
            }
            else{ 
                alert('Error Sending Facial Image!'); 
            }
        });
    }

    /*A page can't be manipulated safely until the document is "ready." 
      jQuery detects this state of readiness for you. Code included inside 
      $( document ).ready() will only run once the page Document Object Model
      (DOM) is ready for JavaScript code to execute.*/
    $(document).ready(function(){
        $('#sendButton').click(function(){
            SendFacialImage();
        });
    });
    </script>
</body>

</html>

The problem I am getting now is the following:

The following is the view function titled AnalyzeFacialImage:

def AnalyzeFacialImage(request):
    if request.method == 'POST':
        if 'data' in request.POST:
            facialImage = request.POST['data']

            context = {
                'facialImage': facialImage,
            }

            width = 300
            height = 300
            newDimensions = (width, height)

            # Load the images and convert them as RGB.
            # We are getting the images as PGR, but the library understands
            # them as RGB.

            # Load image file into a numpy array, which is a grid of non-negative values.
            savedImg = face_recognition.load_image_file('Facial Recognition/khabib1.jpg')

            savedImg = cv2.cvtColor(savedImg, cv2.COLOR_BGR2RGB)
            savedImg = cv2.resize(savedImg, newDimensions, interpolation=cv2.INTER_AREA)

            inputImg = face_recognition.load_image_file('Facial Recognition/khabib3.jpg')
            inputImg = cv2.cvtColor(inputImg, cv2.COLOR_BGR2RGB)
            inputImg = cv2.resize(inputImg, newDimensions, interpolation=cv2.INTER_AREA)

            """
            Find the faces in the images as well as their encodings as well.

            Because we are only sending in a single image, we will only get
            the first element of the image 'savedImg'.
            """

            if len(face_recognition.face_encodings(savedImg)) > 0:
                print("Success! A face was detected for the inputted image.")
            else:
                print("Error! No face was detected for the inputted image.")
                quit()

            # 'faceLoc' will be returned an array that contains the coordinates of a face.
            faceLoc = face_recognition.face_locations(savedImg)[0]  # Send in an image.

            # Encode the face that has been detected.
            encodeKhabib = face_recognition.face_encodings(savedImg)[0]

            # We want to see where we have detected the faces.
            cv2.rectangle(savedImg, (faceLoc[3], faceLoc[0]),
                        (faceLoc[1], faceLoc[2]), (255, 0, 255), 2)

            """
            Check if the 'dlib' face detector was able to find a face in the image.
            If the image contains a face that is turned too sideways rather than
            looking straight into the camera, then the 'dlib' face detector might
            not detect the face.
            """
            if len(face_recognition.face_encodings(inputImg)) > 0:
                print("Success! A face was detected for the inputted image.")
            else:
                print("Error! No face was detected for the inputted image.")
                quit()

            # Send in an image.
            faceLocTest = face_recognition.face_locations(inputImg)[0]

            # Encode the face that has been detected.
            encodeTest = face_recognition.face_encodings(inputImg)[0]

            # We want to see where we have detected the faces.
            cv2.rectangle(inputImg, (faceLocTest[3], faceLocTest[0]),
                        (faceLocTest[1], faceLocTest[2]), (255, 0, 255), 2)

            cv2.imshow("Khabib", savedImg)
            cv2.imshow("Inputted Image", inputImg)

            results = face_recognition.compare_faces([encodeKhabib], encodeTest)

            return render(request, 'users/facial-login-result.html', context)
    else:
        return HttpResponse('Error! Facial Image Not Received.')

Please explain how I can properly pass the JavaScript variable ‘data’ to the view function titled ‘AnalyzeFacialImage’. Thank you!

What is the error message telling you is wrong?

Why do you think that error is being caused by the JavaScript not passing the variable properly to the view?

Are you getting a traceback on the server console? If so, what information does it provide?

Just by looking at the error message, it is clear that it is expecting the view function titled “AnalyzeFacialImage(request)” to return an HTTP response of some sort. Why is this the case?

For some reason, it is still saying “Forbidden (CSRF token missing.): /facial-login-result/” in the terminal even though I have included the csrf token in the form.

The following is what I am seeing in the terminal when I try to submit the facial image:

Besides the csrf token issue, it is also saying the following:
ValueError: The view users.views.AnalyzeFacialImage didn’t return an HttpResponse object. It returned None instead.

It’s what views do. A view accepts a request and returns a Response, in this specific case, an HttpResponse.

This means that all logic flows through the view need to return an HttpResponse. If the view function returns any other type of object, or None, then this error is thrown.

A superficial review of your view shows at least two separate instances where the view can exit without returning an HttpResponse.

But you’re not submitting the form. You’re overriding the default behavior of the submit button and submitting data directly from your JavaScript code.

See the docs at Cross Site Request Forgery protection | Django documentation | Django

Would you say that this is the form is not being submitted to the AnalyzeFacialImage view? How can I get around this? You are saying that I need to include the data from the JavaScript code somewhere in the form right?

No, I’m not saying that.

You’re not submitting a form. You’re making an AJAX-style call. You need to include the csrftoken in what you do submit.

I have included a csrf token in the form, but you are saying that I am not submitting a form.

Image of form:

Image of JavaScript SendFacialImage() function:

Firstly, isn’t it necessary for me to submit the form if my goal is to send the JavaScript variable ‘data’ on line 238 to the AnalyzeFacialImage() view? Or is there an easier way of doing this?

Secondly, where else do I need to include the csrf token given that I have already included it in the form on line 91?