IT Log

Django Tutorial 03 본문

Open Source/Django

Django Tutorial 03

newly0513 2020. 7. 21. 16:19
728x90
반응형

1. View 추가하기

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

 

poslls.urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
    path('<int:question_id>/results/', views.results, name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]


2. View가 동작하게 만들기

polls.views.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)

# detail, results, vote는 수정하지 말고 그대로 유지합니다

여기까지 작성하고 http://127.0.0.1:8000/polls/을 확인하면 What's up?이라는 텍스트만 보입니다. 

 

 

polls/templates/polls/index.html

아래 그림과 같이 폴더(Directory)를 templates와 polls를 만들고 html파일인 index.html파일을 생성합니다. 그 다음 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 %}

 

polls/view.py

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

여기까지 작성하고 http://127.0.0.1:8000/polls/을 확인하면 위에서 작성한 view.py와는 달리 List형식으로 표시되며 클릭도 가능하게 됩니다.

 

 

render()

HttpResponse를 단축해서 작성한다고 보면 됩니다. 화면결과는 같습니다.

 

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


3. 예외처리

polls/view.py

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

from .models import Question
# detail 부분만 수정합니다.
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 }}

 

여기까지 작성하고 http://127.0.0.1:8000/polls/에서 What's up?을 클릭하면 왼쪽 그림과 같이 결과를 보여주는 페이지는 뜹니다. 그러나 주소에서 1이아닌 다른 값을 입력하면 예외처리가 발생하고  코딩에서 작성한 Question does not exist라는 텍스트를 확인할 수 있습니다.

 

 

get_object_or_404

render와 같이 예외처리 시 단축하여 작성하는 방법입니다.

 

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


4. template 시스템 사용하기

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>


5. template에서 하드코딩된 URL 제거하기

polls/templates/polls/index.html

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

 

{% url 'detail' question.id %}에서 detail은 polls/urls.py에서 어떻게 정의되어 있는지 확인할 수 있습니다.


6. URL의 이름공간 정하기

현재는 polls라는 하나의 앱만 진행하지만 여러개가 될 경우 URL을 서로 구분할 수 있어야 합니다. 따라서 app_name이라는 이름공간을 추가하여 구분을 해줍니다.

 

polls/urls.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
    path('<int:question_id>/results/', views.results, name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

 

polls/templates/polls/index.html

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

 

728x90
반응형

'Open Source > Django' 카테고리의 다른 글

Django Tutorial 05  (0) 2020.07.26
Django Tutorial 04  (0) 2020.07.25
Django Tutorial 02  (0) 2020.07.19
Django Tutorial 01  (0) 2020.07.19
Comments