QuintV
QuintV

Reputation: 41

How to make a button in html that can trigger backend functions in Python?

It may seem like I have no idea what I'm doing - which is absolutely correct. Doing a project in which we're pretty much thrown to the wolves. I have never learned HTML, or used any frameworks. Also not too familiar with Python.

The following code is meant to show a list of question titles - when you click on them, you get redirected to a page showing the question, additional text, and various answers.

I want to insert buttons that let you upvote these questions, and each one should be right next (at least close) to the question. When clicked: in the frontend, I only want some visual signal that the user has upvoted, like the button turning orange (so original), or green, whatever. In the backend, I want the button to trigger a static method called vote(question, user), which creates a vote object, to record that the user has upvoted a question. These objects are stored in a database. They contain nothing more but their own auto-generated IDs, the voter/user's ID, and the relevant question's ID.

Ideally, I want the color of the button to depend on the existence of this vote object, but that is really just extras.

And if possible, I want a number to be displayed next to the question, showing the number of votes it has received. To get the num of votes, it should invoke question.get_votes(self), which counts all vote objects that contain the question's ID. I do realize that I could just store this as an attribute with the question and let it increase each time someone voted, but... yeah.

I do not know if arguments are required, and I really don't have a clue on how I'm supposed to do this, even after looking at other threads/googling around.

<ul>
    {% for question in all_questions_with_sub_code %}

    <!-- no idea what i'm supposed to enter here -->
        <li><a href="/question/{{ question.id }}/">{{question.question_title}}</a></li>
    {% endfor %}
</ul>

Upvotes: 2

Views: 1779

Answers (2)

Ajay Kumar
Ajay Kumar

Reputation: 1353

Create your button on HTML and handle the click in JS. Pass the arguments required to Python using AJAX like:

$.ajax({
    method: 'POST',
    url: 'someURL',
    data: {'key': value,
           csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()},
    success: function (data) {},
    error: function (data) {}        
});

Then receive it in Python like this:

def convert(request):
    if request.is_ajax():
        request_data = request.POST
        return HttpResponse(1)

Make sure you handle URL and use CSRF_TOKEN in your HTML

Upvotes: 0

Abijith Mg
Abijith Mg

Reputation: 2693

You need to use combination of Django + Ajax to create smooth voting system without page reload. The following link will get you started:

My Own Like Button: Django + Ajax -- How?

Upvotes: 2

Related Questions