Tutorial 장고 튜토리얼 - 4 : Polls App 2
페이지 정보
본문
장고 튜토리얼에 따라 진행한 과정을 기록하고 설명한 것.
https://docs.djangoproject.com/
-----------------------
장고 튜토리얼 - 4 : Polls App 2 - Polls App 본격 작성
- Django 관리 (Admin)에서 Question과 Choice 추가.
- Question은 설문조사 제목 > Questions에서 + 추가 > Question text : "저메추" 입력 > Date published : 날짜와 시간 입력 > 저장
- Choice는 그 설문조사에 열거할 항목 > Choices + 추가 > Question 선택 : Question object(1) 선택 > Choice text: "김치찌개" 입력 > 저장 > 이런 식으로 여러개 Choice 입력. - view 작성 : polls/views.py from django.http import HttpResponse, HttpResponseRedirectfrom django.shortcuts import get_object_or_404, renderfrom django.urls import reversefrom .models import Choice, Questiondef 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)def detail(request, question_id):question = get_object_or_404(Question, pk=question_id)return render(request, 'polls/detail.html', {'question': 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 += 1selected_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,)))
- url : polls/urls.py from django.urls import pathfrom . import viewsapp_name = 'polls'urlpatterns = [path('', views.index, name='index'),path('<int:question_id>/', views.detail, name='detail'),path('<int:question_id>/results/', views.results, name='results'),path('<int:question_id>/vote/', views.vote, name='vote'),]
- 템플릿 작성 ( polls 디렉토리 내에 templates 디렉토리 그 내에 polls 디렉토리 생성
- index.html : polls/templates/polls/index.html {% if latest_question_list %}<h3>설문조사 목록</h3><ul>{% for question in latest_question_list %}<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>{% endfor %}</ul>{% else %}<p>No polls are available...</p>{% endif %}
- detail.html : polls/templates/polls/detail.html <form action="{% url 'polls:vote' question.id %}" method="post">{% csrf_token %}<fieldset><legend><h1>{{ question.question_text }}</h1></legend>{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}{% 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 %}</fieldset><input type="submit" value="추천"></form>
- results.html : 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 %}">재추천</a>
- index.html : polls/templates/polls/index.html
- 실행
- 브라우저 주소창에 http://127.0.0.1:8000/polls/ 입력 > index.html
- 저메추 클릭 > detail.html
- 첫번째 choice 김치찌개를 선택하고 추천 버튼을 클릭한 결과화면 > results.html
- 브라우저 주소창에 http://127.0.0.1:8000/polls/ 입력 > index.html