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

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.')