TAB Django study 1-3

이준하·2023년 10월 1일

TAB Django

목록 보기
3/5
post-thumbnail

Django tutorial part 3

뷰 작성하기

polls/view.py

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)


def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)


def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

유의사항 : request를 인자로 받고 HttpResponse를 리턴해준다.

urls.py도 수정

from django.urls import path

from . import views

urlpatterns = [
    # ex: /polls/
    path("", views.index, name="index"),
    # ex: /polls/5/
    path("<int:question_id>/", views.detail, name="detail"),
    # ex: /polls/5/results/
    path("<int:question_id>/results/", views.results, name="results"),
    # ex: /polls/5/vote/
    path("<int:question_id>/vote/", views.vote, name="vote"),
]

뷰가 뭔가 하도록 만들기

polls/view.py

from django.http import HttpResponse

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    output = ", ".join([q.question_text for q in latest_question_list])
    return HttpResponse(output)


# Leave the rest of the views (detail, results, vote) unchanged

template 만들기

polls/template/polls/index.html

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

template 사용에 맞게 view 업데이트

from django.http import HttpResponse
from django.template import loader

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    template = loader.get_template("polls/index.html")
    context = {
        "latest_question_list": latest_question_list,
    }
    return HttpResponse(template.render(context, request))

지름길 : render()

polls/view.py

from django.shortcuts import render

from .models import 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)

404 에러 발생시키기

polls/view.py

from django.http import Http404
from django.shortcuts import render

from .models import Question


# ...
def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, "polls/detail.html", {"question": question})

polls/templates/polls/detail.html

{{ question }}

지름길 : get_object_or_404

polls/view.py

from django.shortcuts import get_object_or_404, render

from .models import Question


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

템플릿 사용하기

polls/templates/polls/detail.html

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

템플릿 시스템은 변수의 속성에 접근하기 위해 점-탐색(dot-lookup) 문법을 사용한다. {{ question.question_text }} 구문을 보면, Django는 먼저 question 객체에 대해 사전형으로 탐색한다. 탐색에 실패하게 되면 속성값으로 탐색한다. 만약 속성 탐색에도 실패한다면 리스트의 인덱스 탐색을 시도하게 된다. => ?????

{% for %} 반복 구문에서 question.choice_set.all은 Python에서 question.choice_set.all() 코드로 해석되는데, 이때 반환된 Choice 객체의 반복자는 {% for %}에서 사용하기 적당하다.

템플릿에서 하드코딩된 URL 제거

index.html에서

<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

위 코드를

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

위와 같이 변경

URL의 이름공간 정하기

polls/urls.py에
app_name = "polls"를 작성하여 이름공간 지정

그렇다면 index.html 코드를

<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

위와 같이 변경해야함

Part 3의 추가 내용

<HTTP 상태 코드>
1XX (정보 응답)
2XX (성공 응답)
3XX (리다이렉션 메세지)
4XX (클라이언트 에러 응답)
5XX (서버 에러 응답)
*참고: https://developer.mozilla.org/ko/docs/Web/HTTP/Status

profile
미친 개발자

0개의 댓글