plshelpmeout
plshelpmeout

Reputation: 129

Cannot use the submit button without refreshing page using Django

I'm new to django, and I have setup my project exactly the same way as the tutorial "polls" project. I'm trying to get the page not refreshing or being redirected to another view when I submit an option through a button.

This is my detail.html:

 (...)
 <div class="cardq mt15">
                            <form action="{% url 'polls:vote' question.id %}" method="post">
                                {% csrf_token %}
                                {% for choice in question.choice_set.all %}
                            <!-- New Question -->
                            <div class="cardq__qu">
                                <i class="far fa-question-circle"></i>
                                <!--<p name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
        <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
                                </p>-->
                                <input type="submit" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">                                </div>
                            {% endfor %}
 (...)

I have this on my views.py:

def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
    selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
     return render(request, 'polls/detail.html', {
        'question': question,
        'error_message': "You didn't select a choice.",
    })
else:
    selected_choice.votes += 1
    selected_choice.save()
    return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

What I basically want is to NOT get redirected to results.html and display the results on detail.html without refreshing the page, the same one that had the voting buttons. It's already accurately displaying the poll results on the same page, but if I click one of the buttons, it forces to get redirected to the results page.

Upvotes: 1

Views: 657

Answers (2)

Fydo
Fydo

Reputation: 1424

In order to avoid page refresh, you need to use async requests. Ajax and XMLHttpRequest are the way you would avoid a refresh. These mechanisms let you send data back and forth between browser and server asynchronously (without refresh).

In this scenario, you want to add an event listening to your submit button, prevent a form submit, and trigger an ajax request instead.

Then in the backend, instead of redirect, you want to respond with the poll results (html or json).

In the ajax handler back on the frontend, you'll then need to update or inject the data into wherever you need it to go.

Upvotes: 0

Henok Teklu
Henok Teklu

Reputation: 538

Try looking into working with ajax in django. This is a good starting place.

Upvotes: 2

Related Questions