ruk·si

🍡 Django Tutorial
View Functions

Updated at 2018-11-23 18:24

The simplest way to create pages in Django is to provide a function that receives a HTTP request and returns a HTTP response. Usually you would use view classes but it is good to understand view functions too.

Replace polls/views.py with:

from uuid import UUID

from django.shortcuts import render
from django.http import HttpResponse, HttpRequest

from .models import Question


def index(request: HttpRequest) -> HttpResponse:
    latest_question_list = Question.objects.order_by('-created_at')[:5]
    context = {'latest_questions': latest_question_list}
    return render(request, 'polls/index.html', context)


def detail(request: HttpRequest, question_id: UUID) -> HttpResponse:
    return HttpResponse("You're looking at question %s." % question_id)


def results(request: HttpRequest, question_id: UUID) -> HttpResponse:
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)


def vote(request: HttpRequest, question_id: UUID) -> HttpResponse:
    return HttpResponse("You're voting on question %s." % question_id)

Create polls/templates/polls/index.html:

{% if latest_questions %}
    <ul>
        {% for question in latest_questions %}
            <li>
                <a href="{% url 'detail' question.id %}">{{ question.text }}</a>
            </li>
        {% endfor %}
    </ul>
{% else %}
    <p>No polls available.</p>
{% endif %}

Replace polls/urls.py with:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('<uuid:question_id>/', views.detail, name='detail'),
    path('<uuid:question_id>/results/', views.results, name='results'),
    path('<uuid:question_id>/vote/', views.vote, name='vote'),
]

# You could also use regex:
# re_path('^(?P<question_id>[0-9a-f-]+)/$', views.detail, name='detail'),

Try it out:

python manage.py runserver
# http://localhost:8000/polls/ee72f8f1-4caf-4ad4-bde9-449b37e90690/
# http://localhost:8000/polls/ee72f8f1-4caf-4ad4-bde9-449b37e90690/results/
# http://localhost:8000/polls/ee72f8f1-4caf-4ad4-bde9-449b37e90690/vote/