0

I have a list of things in my html with an ajax request to pass the data-measure value to views.py :

<ul>
   <li><a class="measure" href="#" data-measure="m_0001">Measure_0001</a></li>
   <li><a class="measure" href="#" data-measure="m_0002">Measure_0002</a></li>
   <li><a class="measure" href="#" data-measure="m_0003">Measure_0003</a></li>
</ul>

Javascript

$(".measure").click(function(){
var measure = {'measure': this.getAttribute("data-measure")};
$.ajax({
    url : "prueba/", // the endpoint
    type : "POST", // http method
    data : measure,

    success : function (data) {
         //Success 
    }
});

In this file views.py I want to get the value to make a query to my database.

def prueba(request):
  response_data =  '{}'
  if request.user.is_authenticated:
    if request.method == 'POST':
      measure = request.POST.get('measure', None)
      //request to database

      return JsonResponse(response_data, safe=False)
    else:
      response_data =  '{"nothing to see": "this is not happening"}'
      return JsonResponse(response_data, safe=False)

When I click the item of the list, I have this error:

"Forbidden (CSRF token missing or incorrect.)"

I do not understand where I have to put the csrf_token in order for it to work.

Any suggestions?

MAss
  • 175
  • 1
  • 1
  • 11

1 Answers1

1

Add a hidden input element inside of your ul tag with value as {{ csrf_token }} like this:

<ul>
  <input type='hidden' name='csrfmiddlewaretoken' value='{{ csrf_token }}' />        
  <!-- your list elements -->
</ul>

and then in your jQuery do this:

$("ul .measure").on('click',function(){        
    var measure = {
        'measure': this.getAttribute("data-measure"),
        'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
       };
    // your ajax call
 });
Ahtisham
  • 9,170
  • 4
  • 43
  • 57