adds a view for voting on a question

This commit is contained in:
ergz 2022-07-23 22:56:41 -07:00
parent da055416ee
commit d9eb2540d9
5 changed files with 29 additions and 11 deletions

Binary file not shown.

View File

@ -19,4 +19,4 @@ class Choice(models.Model):
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
return self.choice_text

View File

@ -1,9 +1,12 @@
<h3>Question:</h3>
<p>{{ question.question_text }}</p>
<h3>Available Choices:</h3>
<ul>
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
<legend><h1>{{ question.question_text }}</h1></legend>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
</ul>
</fieldset>
<input type="submit" value="Vote">
</form>

View File

@ -2,6 +2,8 @@ from django.urls import path
from . import views
app_name = "polls"
urlpatterns = [
path("", views.index, name = "index"),
path("<int:question_id>", views.detail, name="detail"),

View File

@ -1,6 +1,7 @@
from django.http import HttpResponse, Http404
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import loader
from django.shortcuts import render
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from .models import Question, Choice
@ -24,4 +25,16 @@ def results(request, question_id):
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("you are voting on question %s" % 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/details.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,)))