장고 튜토리얼 - 4 : Polls App 2 > 장고 DJango

장고 DJango

Tutorial 장고 튜토리얼 - 4 : Polls App 2

페이지 정보

본문

장고 튜토리얼에 따라 진행한 과정을 기록하고 설명한 것. 

https://docs.djangoproject.com/  

----------------------- 


장고 튜토리얼 - 4 :  Polls App 2  - Polls App 본격 작성   
  1.  Django 관리 (Admin)에서 Question과 Choice 추가. 
    - Question은 설문조사 제목 > Questions에서 + 추가 > Question text : "저메추" 입력 > Date published : 날짜와 시간 입력 > 저장 
    - Choice는 그 설문조사에 열거할 항목 > Choices + 추가 > Question 선택 :  Question object(1) 선택 > Choice text: "김치찌개" 입력 > 저장 > 이런 식으로 여러개 Choice 입력. 
    55ba892859ccf01c88442be8dd14173a_1662797136_2999.png
    55ba892859ccf01c88442be8dd14173a_1662797183_6562.png55ba892859ccf01c88442be8dd14173a_1662797168_6023.png


  2.  view 작성 : polls/views.py 
    from django.http import HttpResponse, HttpResponseRedirect
    from django.shortcuts import get_object_or_404, render
    from django.urls import reverse

    from .models import Choice, Question

    def 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 += 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,)))

     

  3.  url : polls/urls.py 
    from django.urls import path
    from . import views

    app_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'),    
    ]
     

  4.  템플릿 작성 ( polls 디렉토리 내에 templates 디렉토리 그 내에 polls 디렉토리 생성 
    1. 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 %}

       
    2. 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>

       
       
    3. 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>

        
  5.  실행 
    1. 브라우저 주소창에 http://127.0.0.1:8000/polls/ 입력  > index.html 
      55ba892859ccf01c88442be8dd14173a_1662801859_2406.png

    2.  저메추 클릭 > detail.html 
      55ba892859ccf01c88442be8dd14173a_1662802190_2726.png
    3. 첫번째 choice 김치찌개를 선택하고 추천 버튼을 클릭한 결과화면 > results.html 
      55ba892859ccf01c88442be8dd14173a_1662802258_5342.png 
장고는? 장고(DJango)는 파이썬(python)으로 제작된 오픈 소스 풀 스택 웹프레임워크입니다.