진박사의 일상

[django] 3일차 Polls App 만들기 - 2 본문

프로그래밍

[django] 3일차 Polls App 만들기 - 2

진박사. 2021. 5. 10. 11:44

여러가지 뷰 추가하기

투표목록, 투표상세, 투표 기능, 투표 결과 뷰를 view.py에 추가

urls.py에서 연결

urlpatterns = [
    #ex: /polls/
    path('', views.index, name='index'), #path(route, view, kwargs, name)
    #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'),
]

URL의 <>안 쪽은 변수를 의미함.

 

동작되는 View를 만들기 위해서 MTV모델에 따라 Templete을 분리한다.

Templetes\polls 추가

intex.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
{% 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 %}
</body>

</html>

view.py에서 해당 view에 추가

latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {
        'latest_question_list': latest_question_list,
        }
    return render(request, 'polls/index.html', context)

render로 빠르게 단축할 수 있다. render(requst, (템플릿), (사전형객체-템플릿에서 사용할 변수들) )

 

404 error 처리

from django.http import Http404

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/1000/ 으로 접근시 1000번째 question이 없으면 404Error를 띄움.

또는

from django.shortcuts import get_object_or_404

question = get_object_or_404(Question, pk=question_id)

으로 try-catch문을 대체 가능

 

하드코딩된 URL 없애기

위의 index.html을 보면 링크 주소가 하드코딩 되어있다.

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

url 템플릿태그를 이용해 'detail'이라는 URL 형식을 urls.py에서 찾아 url 형식으로 만들어 출력함.

 

URL Namespace 설정

앱이 많아지면 동일한 이름을 가진 view가 여러군데 있을 수 있으므로 방지하기 위해 urls.py에 app_name = '(앱 이름)' 을 설정해준다. 그리고 url 템플릿태그에도 'detail' 대신 '(앱 이름):detail'이라고 써 줘야 한다.

 

 

 

나머지는 나중에...