1

I tried to implement a button on a Website, which upon pressing it automatically runs a python function on the server and copies some value into the clipboard of the user. The clipboard copying runs fine, but I can not run the python function.

Whenever I try to I get an error 403 and I think it is due to an issue with the csfr token. Can anyone help me to solve this issue?

Here is my HTML

{% if categories %}
<div class="card shadow mb-4">

    <div class="card-body card-interface">

        <table id="predictionTable" class="table table-bordered">
            <thead>
                <tr>
                    <th>Vorhersage</th>
                    <th>Wahrscheinlichkeit</th>
                    <th>Kopieren</th>
                </tr>
            </thead>
            <tbody>
            {% for category in categories %}
            <tr>
                <td>{{ category.0}}</td>
                <td>{{ category.1}}%</td>
                <td><img src="{% static "documents/img/copy.png" %}" class="interface-copy" value="{{ category.0 }}" input_text = "{{ input_text }}" style="cursor: pointer"></td>
            </tr>
            {% endfor %}
            </tbody>
        </table>

    </div>
</div>
<div id="django-data" data-CSRF="{{csrf_token}}"></div>

And here the .js that is run

  $(".interface-copy").on('click', function(e) {

    var csrftoken = $("django-data").data().CSRF;
    console.log(csrftoken);
    console.log("test")
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(this).attr('value')).select();
    document.execCommand("copy");
    $temp.remove();
    console.log("test")
    $.ajax({
      url: "/ajax/postSingleSourceEntry/",
      type : 'POST',
      beforeSend: function(request){
        request.setRequestHeader("X-CSRFToken", csrftoken);
      },
      data: {
        csfrmiddlewaretoken: csrftoken
      },
      dataType: "json",
      success: function (data){
        console.log("call created")
      },
      error : function(response){
        console.log(response)
      }
    })
  });
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Jonas
  • 43
  • 4

2 Answers2

0

Change:

<div id="django-data" data-CSRF="{{csrf_token}}"></div>

To:

<div id="django-data" data-csrf="{{csrf_token}}"></div>

And:

var csrftoken = $("django-data").data().CSRF;

To:

var csrftoken = $("#django-data").data().csrf;    // Note the # before django-data and csrf in small letter.

You might want to read: How to get the data-id attribute?

Dipen Dadhaniya
  • 4,550
  • 2
  • 16
  • 24
0

You can add @csrf_exempt decorator for that ajax function