Django/DRF

[Django] 첫 번째 장고 앱 작성하기, part4

Jong_seoung 2022. 11. 17. 14:13
반응형

[Django] 첫 번째 장고 앱 작성하기, part4

링크 : https://docs.djangoproject.com/ko/4.1/intro/tutorial04 

 

Django

The web framework for perfectionists with deadlines.

docs.djangoproject.com

 


📖  개요

이 글은 장고 공식 문서를 보고 실습한 내용을 다시 한번 기억하기 위해 쓰면서 정리한 내용입니다. 

 

 

🎯 목표

  • Web-poll 애플리케이션을 진행하였고, 이후 간단한 폼 처리와 소스코드를 줄이는데 목표를 두고 있다.

💡 간단한 폼 쓰기

polls/detail.html을 수정하여, 템플릿에 HTML <form> 요소를 포함시킨다

<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="Vote">
</form>

위 코드를 간략하게 설명하면 :

  • 각 질문 선택 항목에 대한 라디오 버튼을 표시합니다. 각 라디오 버튼의 value는 연관된 질문 선택항목의 ID입니다. 각 라디오 버튼의 name는 "choice"입니다. 즉, 누군가가 라디오 버튼 중 하나를 선택하여 폼을 제출하면, POST 데이터 인 choice = #을 보낼 것입니다. 여기서 #은 선택항목의 id값이다
  • 양식 action을 {% url 'polls:vote' question.id %}로 설정하고 method는 post로 설정합니다. 이 양식을 제출하는 행위는 데이터 서버 측을 변화시키기 때문에  method를 post로 설정하는 것은 매우 중요하다.
  • forloop.counter은 for 태그가 반복을 한 횟수를 나타낸다.
  • post 양식을 만들고 있기 때문에, 교차 사이트 요청 위조에 대해 걱정해야 하지만 Django는 그것으로부터 보호하는 유용한 시스템을 가지고 있다. 간단히 말하면 내부 URL을 대상으로 하는 모든 POST 양식은 {% csrf_token %} 템플릿 태그를 사용해야 한다.

💡제출된 데이터를 처리하고 수행하는 Django뷰 작성

(polls/urls.py)

path('<int:question_id>/vote/', views.vote, name='vote'),

 

💡 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()

        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

위 코드는 아직 배우지 않은 몇의 코드를 가지고 있다.

  • request.POST는 키로 전송된 자료에 접근할 수 있도록 해주는 딕셔너리와 같은 객체입니다. 위 코드의 경우 request.POST ['choice']는 선택된 설문의 ID를 문자열로 반환합니다. request.POST의 값은 항상 문자열들입니다.
  • 만약 POST자료에 choice가 없으면 request.POST['choice']는 KeyError이 나오고 choice가 주어지지 않은 경우에는 에러 메시지와 함께 설문조사 폼을 다시 보여줍니다.
  • 설문자 수가 증가한 이후에는, 코드는 일반 HttpResponse 가 아닌 HttpResponseRedirect를 반환하고, HttpResponseRedirect는 하나의 인수를 받습니다
  • 이 예제는 HttpResponseRedirect 생성자 안에서 reverse() 함수를 사용하고 있습니다. 이 함수는 뷰 함수에서 URL을 하드 코딩하지 않도록 도와줍니다.

💡 결과 페이지 리다이렉트

(polls/views.py)

from django.shortcuts import get_object_or_404, render


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

(polls/templates/polls/result.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>

위처럼 작성하고 나면 투표를 하면 값이 반영된 결과 페이지를 볼 수 있다. 또한 질문을 선택하지 않고 폼을 전송했다면, 오류 메시지를 볼 수 있다.

 

💡  제너릭 뷰 사용하기

detail()과 results()의 view들은 매우 간단하며 중복이 된다. 또 여론 조사 목록을 보여주는 index() view도 매우 비슷하다.

제너릭 뷰는 일반적인 패턴을 추상화하여 앱을 작성하기 위해 python 코드를 작성하지 않아도 된다.

 

설문 조사 애플리케이션은 제너릭 뷰 시스템으로 변환해서 우리의 코드를 많이 삭제하게 도와준다.

  1.  URLconf를 변환한다.
  2. 불필요한 오래된 보기 중 일부를 삭제한다.
  3. Django의 제너릭 뷰를 기반으로 새로운 뷰를 도입한다.

📑 URLconf 수정

(polls/url.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'),
]

두 번째와 세 번째 패턴의 경로 문자열에 일치하는 패턴들의 이름이 <question_id>에서 <pk>로 변경되었습니다.

📑 view 수정

다음으로 이전 index, detail, results 뷰를 제거하고 장고의 일반적인 뷰를 사용한다. (polls/view.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.

ListView와 DetailView의 두 가지 제너릭 뷰를 사용하고 있습니다. 이 두 보기는 각각 "객체 목록 표시" 및 "특정 개체 유형에 대한 세부 정보 페이지 표시" 개념을 추상화합니다.

  • 각 제너릭 뷰는 어떤 모델이 적용될 것인지를 알아야 합니다. 이것은 model 속성을 사용하여 제공됩니다.
  • DetailView 제너릭 뷰는 URL에서 캡처된 기본 키 값이 "pk"라고 기대하기 때문에 question_id를 제너릭 뷰를 위해 pk로 변경합니다.

기본적으로 DetailView 제너릭 뷰는 <app name>/<model name> _detail.html 템플릿을 사용합니다. 우리의 경우에는 "polls/question_detail.html" 템플릿을 사용할 것이다. template_name 속성은 Django에게 자동 생성된 기본 템플릿 이름 대신에 특정 템플릿 이름을 사용하도록 알려주기 위해 사용된다. results 리스트 뷰에 대해서 template_name을 지정합니다. 

 

마찬가지로, ListView 제네릭 뷰는 <app name>/<model name>_list.html 템플릿을 기본으로 사용합니다; 이미 있는 "polls/index.html" 템플릿을 사용하기 위해 ListView에template_name를 전달했습니다.

 

이전 부분에서 템플릿은 question  latest_question_list 컨텍스트 변수를 포함하는 컨텍스트와 함께 제공되었습니다. DetailView의 경우 question 변수가 자동으로 제공되는데, 이는 우리가 Django 모델(Question)을 사용하고 있기 때문에 Django가 컨텍스트 변수의 적절한 이름을 결정할 수 있습니다. 그러나 ListView의 경우 자동으로 생성되는 컨텍스트 변수는 question_list입니다. 이것을 덮어 쓰려면 context_object_name 속성을 제공하고, 대신에 latest_question_list를 사용하도록 지정해야 한다. 새로운 기본 컨텍스트 변수와 일치하도록 템플릿을 변경할 수도 있지만, 원하는 변수를 사용하도록 Django에게 지시하는 것이 훨씬 쉽습니다.

 

과제 - 서버를 실행하고 제너릭 뷰를 기반으로 한 새 설문조사 앱을 사용하세요

반응형