HttpResponse - 객체를 반환
#polls.views.py
from django.http import HttpResponse
...
return HttpResponse(output)
render() - HttpResponse 객체와 함께 돌려주는 구문을 쉽게 표현할 수 있도록 하는 단축 기능
#polls.views.py
from django.shortcuts import render
...
return render(request, 'polls/index.html', context)
Http404 - 404에러 일으키기
from django.http import Http404
from django.shortcuts import render
from .models import Question
...
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})
get_object_or_404() - Http404 예외를 발생시키는 단축기능
from django.shortcuts import get_object_or_404, render
from .models import Question
...
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
#polls/index.html
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
<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>
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']) # 선택된 설문의 ID를 문자열로 반환
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.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,)))
```
class IndexView(generic.ListView):
template_name = 'polls/index.html' # "polls/index.html" 템플릿을 사용하기 위해 ListView 에 template_name 를 전달
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' # <app name>/<model name>_detail.html 템플릿을 사용