Listing the Questions on index.html
In view.py under index function get the list of question and store them in an object then pass them to the url
# Get questions and display them
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
Edit index.html
Poll Questions
{% if latest_question_list %}
{% for question in latest_question_list %}
{% endfor %}
{% else %}
No polls available
{% endif %}
{% endblock %}
Create Showing Specific Question’ View, Url & Template
In view.py create another function, find the question using its id then pass it as a dictionary to the url
# Show specific question and choices
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', { 'question': question })
Add the url to polls/urls.py
path('/', views.detail, name='detail'),
Create the template: create detail.html
{{ question.question_text }}
{% if error_message %}
{{ error_message }}
{% endif %}
{% endblock %}
Create Show Results’ View, Url & Template
In view.py create another function, find the question using its id then pass it as a dictionary to the url
Create Vote’s View, Url
In view.py create another function, find the question using its id then pass it as a dictionary to the url
but first make sure to import reverse, 404, http packages
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
# Vote for a question choice
def vote(request, question_id):
# print(request.POST[‘choice’])
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST[‘choice’])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, ‘polls/detail.html’, {
‘question’: question,
‘error_message’: “You didn’t select a choice.”,
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse(‘polls:results’, args=(question.id,)))
Add the url to polls/urls.py
path('/vote/', views.vote, name='vote')
Create Nav and Partial Templates
In templates folder create a folder partials and create a file _navbar.html the _ means it’s partial, not a full template
Then include it the base.html file
{% include 'partials/_navbar.html' %}