title: Django Ajax Post Request by Using Checkbox in CBV
body: <p>I'm trying to send ajax post requests to my server to add or remove objects by using just checkboxes (not form). Here is a screenshot of what I got visually: </p>
  
  <p><a href="https://pasteboard.co/IMHHSa6.png" rel="nofollow noreferrer">https://pasteboard.co/IMHHSa6.png</a></p>
  
  <p>When I click any of the checkboxes I got http500 (internal server error) as response. In cmd I see the error that says there is no matching query: <strong>app1.models.Influencer.DoesNotExist: Influencer matching query does not exist.</strong></p>
  
  <p>The thing is I'm pretty sure that the object with that id exists in the database. I spend much time inspecting Django's CSRF documentation and watching youtube videos about django-ajax examples. Here is my code:</p>
  
  <p><strong>views.py</strong>:</p>
  
  <pre><code>class InfluencerListView(LoginRequiredMixin, ListView):
      model = Influencer
      context_object_name = 'influencers' # not necessary, default is object_list
  
      def post(self, request, *args, **kwargs):
          inf_id = request.POST.get('inf.id')
          list_id = request.POST.get('list.id')
          i = Influencer.objects.get(id=inf_id)
          l = InfluencerList.objects.get(id=list_id)
          l.influencers.add(i)
          data = {
                  'result' : 'some result'
          }
          return JsonResponse(data)     
  
      def get_context_data(self, **kwargs):
          context = super().get_context_data(**kwargs)
          logged_in_user = self.request.user
          context['myLists'] = logged_in_user.lists.annotate(influencers_count=Count('influencers'))
          return context
  </code></pre>
  
  <p><strong>models.py:</strong></p>
  
  <pre><code>class Influencer(models.Model):
      # fields are not included for the sake of clarity
  
  class InfluencerList(models.Model):
      name = models.CharField('Name:', max_length=20, blank=False)
      owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists')
      influencers = models.ManyToManyField('Influencer', related_name='lists') 
  </code></pre>
  
  <p><strong>scripts.js</strong></p>
  
  <pre><code>function getCookie(name) {
      var cookieValue = null;
      if (document.cookie &amp;&amp; document.cookie !== '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i &lt; cookies.length; i++) {
              var cookie = cookies[i].trim();
              // Does this cookie string begin with the name we want?
              if (cookie.substring(0, name.length + 1) === (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      return cookieValue;
  }
  
  function csrfSafeMethod(method) {
      // these HTTP methods do not require CSRF protection
      return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }
  
  function myFunc(_self) {
      inf_id = _self.getAttribute('data-inf_id');
      list_id = _self.getAttribute('data-list_id');
      console.log(inf_id + " " + list_id); # I CAN SEE THOSE  IDS IN CONSOLE AND THEY EXIST IN DB
      var csrftoken = getCookie('csrftoken');
      if(_self.checked == true){
          console.log("checked!");
  
          $.ajaxSetup({
              beforeSend: function(xhr, settings) {
                  if (!csrfSafeMethod(settings.type) &amp;&amp; !this.crossDomain) {
                      xhr.setRequestHeader("X-CSRFToken", csrftoken);
                  }
              }
          });
  
          $.ajax({
              method: 'POST',
              url: '/influencers',
              data: {
                  'inf_id': inf_id,
                  'list_id': list_id,
                  'csrfmiddlewaretoken': csrftoken
              },
              dataType: 'json',
              success: function (data) {
                  console.log("succes!");
              }
          });
      }
      else{
           console.log("unchecked!");       
      }
  }
  </code></pre>
  
  <p>I also added this line somewhere in my view file (where I put it doesn't matter as long as it's in the body since I'm not using any forms. Please correct me if I'm wrong):</p>
  
  <pre><code>&lt;input type='hidden' name='csrfmiddlewaretoken' value='{{ csrf_token }}' /&gt;        
  </code></pre>