how to use ensure_csrf_cookie right way ?

:one: models.py

class Post(models.Model):
    poster = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField(max_length=500)
    timestamp = models.DateTimeField(default=timezone.now)
    likes = models.ManyToManyField(User, blank=True, related_name='likes')

:two: views.py

@ensure_csrf_cookie
def index(request):
    if request.method == 'POST':
        print(request.POST['postid'])
        print(request.POST['postcontent'])
        return JsonResponse({"message": 1})
    else:
        posts = Post.objects.all()
        paginator = Paginator(posts, 10)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
        return render(request, "network/index.html", {'page_obj': page_obj, 'form': PostForm})

:three: index.js

document.querySelectorAll(".editButton").forEach((button) => {
    button.onclick = function (e) {
      const form = document.querySelector(`#form-post-edit-${e.target.id}`);
      const textArea = document.createElement("textarea");
      const buttonSubmit = document.createElement("input");
      textArea.setAttribute("name", "content-edit");
      textArea.setAttribute("cols", "40");
      textArea.setAttribute("rows", "10");
      textArea.setAttribute("maxlength", "500");
      textArea.setAttribute("data-post-id", e.target.id);

      textArea.required = true;
      buttonSubmit.setAttribute("type", "submit");
      buttonSubmit.setAttribute("value", "EditSave");
      form.append(textArea);
      form.append(buttonSubmit);
      document.querySelector(`#form-div-${e.target.id}`).style.display =
        "block";
      document.querySelector(`#content-${e.target.id}`).style.display = "none";

      document.querySelector(`#form-post-edit-${e.target.id}`).onsubmit = (
        e
      ) => {
        e.preventDefault();
        const csrftoken = document.querySelector("[name=csrfmiddlewaretoken]")
          .value;
        const content = document.querySelector("#id_content_edit").value;
        const postid = document.querySelector("#id_content_edit").dataset
          .postId;
        fetch("", {
          method: "POST",
          mode: "same-origin",
          headers: { "X-CSRFToken": csrftoken },
          body: JSON.stringify({
            postid: postid,
            postcontent: content,
          }),
        })
          .then((res) => {
            console.log(res);
          })
          .catch((res) => console.warn(res));
      };
    };
  });

:three: What requires ?

  • on default url , user can edit their posts
  • trying to add form dynamically, so used ensure_csrf_cookie
  • post setting decorator, how javascript is able to generate token using fetch api(POST)
  • from fetch data, ORM will update db record if that post

Everything needed for using the CSRF protection is covered in the Cross Site Request Forgery protection page.