TAB Django study 2-1

이준하·2023년 10월 9일

TAB Django

목록 보기
4/5
post-thumbnail

Django tutorial part 4

간단한 폼 만들기

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

{% if error_message %}

{{ error_message }}

{% endif %} -> 에러 메시지 받으면 에러 메시지 보여준다

form 태그
input 태그 : 사용자의 입력을 받을 수 있는 태그
label 태그 : 이름을 보여주는 태그

method="post" -> 나중에 rest api 때 배울거임

{% csrf_token %} -> 사이트 간 위조 요청(해킹) 방지용으로 사용하는거임 / 사이트 간 위조 요청 : 사용자와 서버 사이의 데이터를 해커가 임의로 변경

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

question.choice_set.get -> question에 대해서 외래키를 갖는 선택지를 가져온다.

pk=request.POST["choice"] -> 선택지 중에서 pk값이 template에서 넘겨받은 값을 조회. request.POST에서 choice의 데이터를 가져와라

return HttpResponseRedirect(reverse("polls:results", args=(question.id,))) -> post로 뷰를 호출했을 경우에 return 해준다 / POST랑 세트다.

reverse : url 하드 코딩하지 않으려고 사용

polls/view.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})

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>

{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }} : pluralize는 vote가 단수 인 경우에는 단수처리하고 복수인 경우에는 복수처리 한다. (장고에서 제공하는 기능)

제네릭 뷰(클래스 기반 뷰)

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

pk : db 내의 하나의 열, 하나의 데이터를 구분할 수 있는 값

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"),
]

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.

get : 데이터 조희를 위한 요청 방식

Part 4의 추가 내용

generic view란?
장고에서 기본적으로 제공하는 view 클래스
ex) Listview, Detailview, Formview 등
장) 코드가 훨씬 간단해짐.
단) 추상화 시키게 됨 -> 이름만 보고 어떤지 유추하기 힘들어짐, 읽기 어려움.
즉, generic view는 양날의 검

profile
미친 개발자

0개의 댓글