본문 바로가기
lang/Django

Django 앱 작성하기 part4 [form]

by Wordbe 2019. 7. 12.
728x90

투표(vote) 양식 만들기

  • 반영사항-
    POST 데이터를 처리한 후에는 항상 HttpResponseRedirect를 반환해야 한다.

polls/views.py

from django.shortcuts import get_object_or_404, render

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})

polls/templates/polls/results.html

<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>

vote 적용
vote 결과 반영

Generic View : 가독성 좋고, 코드량 적음

URLconf 수정

polls/urls.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

polls/views.py

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic

from .models import Choice, Question


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'


def vote(request, question_id):
    ... # same as above, no changes needed.

generic.ListView
appname/modelname_list.html 템플릿을 기본으로 사용
question_list 변수 제공,
덮어쓰고 싶다면, context_object_name에 'latest_question_list' 를 대입

generic.DetailView
question 변수가 자동으로 생성

728x90

'lang > Django' 카테고리의 다른 글

Django 앱 작성하기 part5 [test]  (4) 2019.07.12
Pycharm 단축키  (255) 2019.07.12
Django 앱 작성하기 part3 [view]  (242) 2019.07.12
Django 앱 작성하기 part2 [model]  (613) 2019.07.11

댓글