1

I have the following button: <a class="btn btn-success">Accept</a>. Like this previous stack overflow question, I want to call my view after the button is clicked, but I can not seem to get it to work.

What I have tried: Using AJAX, treating button like a form, requesting post data, but this does not seem to work.

How can I make it so when my button is clicked, I call the bellow view?

def acceptdonation(request, pk):
    Donation.objects.filter(pk=pk).update(views=F('views')+1)
    return HttpResponseRedirect(request.GET.get('next')))

2 Answers2

0

If you want to post a form to a view you can use this:

function submitToView() {
    var formData = new FormData(); 
    formData.append('some_variable', 'abc'); 
    var xhr = new XMLHttpRequest();
    
    xhr.onreadystatechange = function () {
      if (xhr.readyState == XMLHttpRequest.DONE) {
  
        abc = JSON.parse(xhr.responseText);
    
      }
    }
  
    xhr.open('POST', '/my_view/', true);
    xhr.setRequestHeader("X-CSRFToken", csrftoken);
    xhr.send(formData);
  }

Please consider adding your javascript with html and your urls.py

Walucas
  • 2,549
  • 1
  • 21
  • 44
  • Thank you for the detailed response, but I was wondering if I could do this without using javascript? In the example stack overflow question I included, someone was able to do it with a default django url –  Jul 27 '21 at 18:24
  • sure, share your code, it will facilitate – Walucas Jul 27 '21 at 18:25
-1

In your template link to the view you want:

<a href="{% url 'myapp:myview' %}" class="btn btn-success">Accept</a>

Of course you can also pass a pk or other data to the url if you need to.

michjnich
  • 2,796
  • 3
  • 15
  • 31