Forbidden (403) CSRF verification failed. Request aborted even though the csrf token is present

60 views Asked by At

I am making a project in Django for an NGO. I keep running in the csrf toke missing error. I have the {% csrf_token %} tag in the form tags. The csrf is working on other forms but isn't working on this form only.

enter image description here

here is the html page that is resulting in this error:

{% load static %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Assistanza</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous" />



</head>

<body>
    <!--NavBar -->
    <nav class="navbar navbar-expand-lg">
        <div class="container-fluid">
            <a class="navbar-brand" href="#"><img src="{% static 'main/images/navbarlogo.jpg' %}" alt="Logo" width="80"
                    height="40" class="d-inline-block align-text-top" /></a>
            <div class="container marketing">
                <div id=timer></div>
            </div><br><br><br>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">

                </ul>
            </div>
        </div>
    </nav>

    <div><br><br></div>
    <script>
        var timeLimit = {{ time_limit }};
        var timer = setInterval(function () {
            var minutes = Math.floor(timeLimit / 60);
            var seconds = timeLimit % 60;

            // Display time in minutes and seconds
            document.getElementById('timer').innerHTML =
                'Time Left: ' + minutes + 'm ' + seconds + 's';

            // Check if time is up
            if (timeLimit <= 0) {
                clearInterval(timer);
                // Redirect to the completion page
                window.location.replace("{% url 'test_complete' %}");
            }

            timeLimit--;
        }, 1000); // Update every 1 second
    </script>

    <div class="container marketing">
        <form class="form" autocomplete="off" onsubmit="return saveAns()" action="{% url 'test_complete' %}"
            method="POST">
            {% csrf_token %}
            {% for q in questions %}


            <h3 class="text-primary">{{ forloop.counter }}. {{q.question}}</h3>
            <!-- 
            <input type="hidden" name="csrfmiddlewaretoken"
                value="C24rUotmdHawVQJL3KrqiWxvti8UffOFYUc8TRbZtLt36AVLdP3jbkzUVe3beRAa"> -->


            <div class="form-check mx-4">
                <input class="form-check-input" type="radio" name="{{ q.course }} {{forloop.counter}}"
                    id="{{q.option1}}" value="Option1">
                <label class="form-check-label" for="option1">
                    {{q.option1}}
                </label>
            </div>


            <div class="form-check mx-4">
                <input class="form-check-input" type="radio" name="{{ q.course }} {{forloop.counter}}"
                    id="{{q.option2}}" value="Option2">
                <label class="form-check-label" for="option2">
                    {{q.option2}}
                </label>
            </div>


            <div class="form-check mx-4">
                <input class="form-check-input" type="radio" name="{{ q.course }} {{forloop.counter}}"
                    id="{{q.option3}}" value="Option3">
                <label class="form-check-label" for="option3">
                    {{q.option3}}
                </label>
            </div>


            <div class="form-check mx-4">
                <input class="form-check-input" type="radio" name="{{ q.course }} {{forloop.counter}}"
                    id="{{q.option4}}" value="Option4">
                <label class="form-check-label" for="option4">
                    {{q.option4}}
                </label>
            </div><br><br>
            {% endfor %}
            <br><br><br>
            <input class="btn btn-info btn-lg btn-secondary" type="submit" value="Submit">
        </form>
    </div>
    <br><br>
    <div class="container">
        <footer class="py-3 my-4">
            <ul class="nav justify-content-center border-bottom pb-3 mb-3">
                <li class="nav-item"><a href="{% url 'home page' %}" class="nav-link px-2 text-body-secondary">Home</a>
                </li>
            </ul>
            <p class="text-center text-body-secondary">© Made By : <a
                    href="https://www.instagram.com/adiviki_p?igshid=OGQ5ZDc2ODk2ZA==">Adityavikram </a></p>
        </footer>
    </div>

    <script>


        function saveAns() {

            var ele = document.getElementsByTagName('input');
            for (i = 0; i < ele.length; i++) {
                if (ele[i].type = "radio") {
                    if (ele[i].checked) {
                        setCookie(ele[i].name, ele[i].value, 3)
                    }
                }
            }

        }

        function setCookie(cname, cvalue, exdays) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
            var expires = "expires=" + d.toUTCString();
            document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
        }

    </script>

    <br><br><br><br><br><br>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous">
        </script>
</body>

</html>

Here is the views.py function for the same:

def start_exam10 (response):
    # course=QMODEL.course.objects.get.all()
    questions=QMODEL.objects.all().filter(standard = '10th')
    timelimit = 50
    class10topics = ['uniserv', 'technical', 'health','commerce','arts','agri']
    return render (response ,"main/testpage10.html", {'questions':questions,'time_limit': timelimit } )

and here is the url.py file:

from django.urls import path 
from . import views 
from django.contrib.staticfiles.urls import staticfiles_urlpatterns


urlpatterns =[
    path("", views.homepage, name = "home page"),
    path ("class10.html/" , views.class10 , name = "Class 10th"),
    path ("class12.html/", views.class12, name ="class 12"),
    path ("class10.html/testlanding.html/", views.validating_users, name ="pre test infofor 10"),
    # path ("class12.html/testlanding.html/", views.validating_users, name ="pre test infofor 12"),
    path ("class10.html/testlanding.html/testinstruction.html/", views.test_instruction, name ="pre test info"),
    path ("class12.html/testlanding.html/testinstruction.html/", views.test_instruction, name ="pre test info"),
    path ("testpage10.html", views.start_exam10, name ="test_page10"),
    path ("testpage12.html", views.start_exam12, name ="test_page12"),
    path ("testresult.html", views.end_exam, name ="test_complete"),
    path ("testpage.html", views.testing_csrf, name ="testing_error"),
    #path ("testing_csrf_result.html", views.testing_csrf, name ="result of csrf"),

]

I have also added the following after reading online :

CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:8000/', 'http://127.0.0.1:8000/testpage10.html']
0

There are 0 answers