ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Django tutorial] django official tutorial part4 정리
    Software, Computer Science/Django, Flask 2020. 2. 3. 22:15

    Part 4

     

    설문 form에 맞게 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>
    

     

    • 참고) 여기서 주목할 점은 {% csrf_token %} 부분인데 POST작업을 수행할 때 발생할 수 있는 CSRF(Cross Site Request Forgeries - 인터넷 사용자가 자신의 의지와는 무관하게 공격자가 의도한 행위(수정, 삭제, 등록 등등)를 특정 웹사이트에 요청하게 만드는 공격)보안 문제를 발생시키지 않기 위해 간단히 처리하는 template부분이다.

     

    views.py 안에 있는 vote()를 다음과 같이 구현한다.

     

    # 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 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,)))
    

     

    • request.POST는 key로 전송된 자료에 접근할 수 있도록 해주는 dictionary -> value들은 모두 string으로 구성
    • except 부분에서 choice를 하지 않을 때 detail.html을 에러 메세지를 발생시키고 form을 다시 보여줌(예외처리)
    • 설문이 끝나는 부분에서 HttpResponseRedirect 생성자를 사용하는데 vote이후 재전송 되게끔 처리하는 부분이다. argument로 재전송 되는 url을 넣으면 됨
    • 해당 생성자 안에 reverse() 를 사용하는데 이 부분은 URL을 하드코딩하지 않게 처리하는 부분. 앞 장에서 봤던 URLConf를 사용

     

    results view 다시 완성

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

     

    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 %}">Vote again?</a>
    

     

    Generic view 사용 : 같은 기능이면 코드의 양이 적게

     

    지금까지 해오면서 웹개발은 다음과 같이 요약될 수 있다.

    URL에서 전달 된 매개 변수에 따라 데이터베이스에서 데이터를 가져 오는 것과 템플릿을 로드하고 렌더링 된 템플릿을 리턴하는 기본 웹 개발의 일반적인 경우

     

    django에선 이런 일반적인 경우를 generic view system으로 구성하여 class의 형태로 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'),
    ]
    

     

    views.py를 아래와 같이 수정

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

     

    class의 상속 부분을 잘 확인해보면 generic view는 크게 ListViewDetailView를 사용하고 있다.

    • 각 generic view는 어떤 모델이 적용될 것인지 알아야 하고 이 부분은 model 변수(속성)을 사용하여 정의된다
    • ListView, DetailView generic view는 <app name>/<model name>_detail.html 템플릿으로 사용한다. template_name은 앞서 언급했던 바와 같이 자동생성 되는 이름 대신에 해당 template_name을 사용하라고 재정의 해주는 부분이다.

     

    정리

    위와 같이 part1 ~ 4 까지 django tutorial 내용을 필요하다고 생각하는 것 만큼, 알아야 한다고 생각하는 만큼 정리했다. 아직 기본 개념과 배경지식이 부족해 완벽히 정리하진 못했지만 실제로 웹개발을 잘 하기 위해서 고려해야 할 사항들이 적지 않다는 것을 다시 한 번 느낀 것 같다.

     

    튜토리얼에서 실제로 템플릿을 많이 썼지만 요즘 개발 트렌드에는 알맞지 않다 요즘 개발 트렌드에서 template을 합쳐 full-stack으로 구현하는 추세가 아니기에 template 부분은 거의 만들지 않고 FE 개발로 그 역할이 넘어가 있는 편이다. 따라서 템플릿은 일단 참고로 알아 두고 정 필요하다 싶으면 찾아가며 쓰는 정도로 정리해두는게 맞을 듯 싶다.

     

    Reference

    https://docs.djangoproject.com/ko/3.0/intro/tutorial04/

    댓글

Designed by Tistory.