[Django] 05.간단한 폼처리와 소스코드 줄이기
첫번째 장고 앱 작성하기, part 4
간단한 폼 만들기
- polls/detail.html을 변경해보면
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
polls/urls.py path('<int:question_id>/vote/', views.vote, name='vote'),
- polls/views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from .models import Choice, Question
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
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):
# 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,)))
- 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>
Generic View 사용하기
더욱더 간결한 코드를 작성하기 위해서 URLconf 수정
를 로 변경
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'),
]
조회수 수정
- index, detail, results 뷰를 제거하고 장고의 일반적인 뷰를 사용.
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
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.
ListView와 DetailView의 두 가지 제네릭 뷰를 사용.
참고
'Python > Django' 카테고리의 다른 글
[Django] 각종 유용한 패키지 (0) | 2021.04.29 |
---|---|
[Django] 08.관리자 폼 커스터마이징 (0) | 2021.04.29 |
[Django] 07.스타일시트와 이미지 추가 (0) | 2021.04.29 |
[Django] 06.자동화된 테스트 (0) | 2021.04.29 |
[Django] 04. 어플리케이션 View 만들기 (0) | 2021.04.29 |
[Django] 03.데이터베이스 연동하기(migration, model 생성) (0) | 2021.04.29 |
[Django] 02.프로젝트 만들기 및 시작하기 (간단한 설문조사 어플리케이션 만들기) (0) | 2021.04.29 |
[Django] 01. 설치 및 환경 설정 (0) | 2021.04.29 |