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 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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
sure, share your code, it will facilitate
-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.