skip to Main Content

I’ve a question, I am a Django developer, in my program I want to write a JavaScript file that when we click a button, the script file create a new form. The javaScript file:

function noid(){
    console.log("on");
    const mydiv = document.querySelector(".my");
    const myform = document.createElement("form");
    mydiv.appendChild(myform);
    myform.insertAdjacentHTML("afterend",
    "{% csrf_token %}")

 

    
    
    
}
document.querySelector("#mybtn").addEventListener("click",noid);

The html file:

{% extends "base.html" %}
{% load static %}
{% block head %}
<title>create</title>
<link rel="stylesheet" href="{% static "sakht.js" %}">


<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@200&display=swap" rel="stylesheet">
{% endblock head %}
{% block body %}


<div class='container bg-ligth rounded-3 my'>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">submit</button>
    </form>

    <button class="Mybtn" id="mybtn">Add</button>
    <form method="post">
        {% csrf_token %}
        {{ quesform.as_p }}
        <button type="submit">submit</button>
    </form>
</div>


<script src="{% static "sakht.js" %}"></script>
{% endblock body %}

I want to know that how can I add the {% csrf_token %} block and {{ quesfrom.as_p }} block to javascript file. please help me.

How can I add {% csrf_token %} and {{ quesform.as_p }} blocks to javascipt?

2

Answers


  1. You can’t directly include Django template tags like {% csrf_token %} and {{ quesform.as_p }} in a separate JavaScript file because Django template tags are processed on the server side, and JavaScript runs on the client side.

    You can include the CSRF token in a meta tag in the HTML and then retrieve it using JavaScript. Similarly, you can fetch the form HTML from the server using an AJAX request.

    Here’s an example of how you can modify your code to achieve this:

    In your HTML template, include the CSRF token in a meta tag:

    {% block head %}
      <meta name="csrf-token" content="{% csrf_token %}">
      <!-- other head content -->
    {% endblock head %}
    

    Modify your JavaScript file to retrieve the CSRF token and form HTML:

    function noid() {
        console.log("on");
        const mydiv = document.querySelector(".my");
        const myform = document.createElement("form");
    
        // Retrieve CSRF token from the meta tag
        const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
    
        // Add CSRF token to the form
        myform.insertAdjacentHTML("beforeend", `<input type="hidden" name="csrfmiddlewaretoken" value="${csrfToken}">`);
    
        // Fetch form HTML using AJAX
        fetch('/quesform-path/', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
        })
        .then(response => response.text())
        .then(data => {
            myform.insertAdjacentHTML("beforeend", data);
            mydiv.appendChild(myform);
        })
        .catch(error => console.error('Error:', error));
    }
    
    document.querySelector("#mybtn").addEventListener("click", noid);
    

    Replace /quesform-path/ with the actual URL endpoint that serves your quesform.as_p content.

    Login or Signup to reply.
  2. Your separate JS cannot contain the CSRF token. You will need to embed it somehow into your main page. You could embed it into a meta tag as Azury’s answer describes, or you can embed it into a Javascript script, like

    <script>
        var csrf = "{% csrf_token %}";
    </script>
    

    and then you will be able to refer to it as:

    function noid(){
        console.log("on");
        const mydiv = document.querySelector(".my");
        const myform = document.createElement("form");
        mydiv.appendChild(myform);
        myform.insertAdjacentHTML("afterend", csrf);
    }
    document.querySelector("#mybtn").addEventListener("click",noid);
    

    The reason is that CSRF can only be defined by the server (that’s the whole point) and therefore you need to evaluate it on your server.

    If you want to generate it into your js file, then you need to generate it on the server-side upon each request, which would be a self-defeating approach, given the fact that your file cannot be reliably cached then. But the point of the caching approach by the browser (and sometimes on the server as well) is to make sure that the resource is not generated/sent each time it’s needed.

    So it’s better to find a main layout, embed the csrf into it and use it on your js script codes as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search