본문 바로가기

Python_WEB/Django_Tutorial

[Django]Survey WEB Application Tutorial 4

1. 설계 계획 수립

질문 "색인" 페이지 -- 최근의 질문들을 표시합니다.
질문 "세부" 페이지 -- 질문 내용과, 투표할 수 있는 서식을 표시합니다.
질문 "결과" 페이지 -- 특정 질문에 대한 결과를 표시합니다
투표 기능 -- 특정 질문에 대해 특정 선택을 할 수 있는 투표 기능을 제공합니다.

 

2. 뷰 추가

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

 

3. path() 호출 추가 후 polls.urls 모듈 연결

 

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

detail() 함수를 호출하여 URL 에 입력한 ID 를 출력

 

4. index() views 생성

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

# 나머지 견해 (세부 사항, 결과, 투표)는 변경하지 마십시오.

 

5. index.html 생성

'''
polls/templates/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 %}

 

* 템플릿 네임스페이싱

Django는 이름이 일치하는 첫 번째 템플릿을 선택하며, 다른 응용 프로그램에서 동일한 이름을 가진 템플릿이 있으면

Django는 템플릿을 구별 할 수 없습니다.

Django가 올바른 것을 가리킬 수 있어야하며, 이를 보장하는 가장 좋은 방법은 이름을 지정하는 것입니다.

즉, 해당 템플릿을 응용 프로그램 자체의 다른 디렉토리에 넣습니다.

 

 

 

6. index() views 수정

 polls/index.html 템플릿을 불러온 후, context(템플릿에서 쓰이는 변수명과 Python 객체를 연결하는 사전형 값)를 전달

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

 

7. rander() 사용

지정된 템플릿을 지정된 컨텍스트 사전과 결합하고 해당 렌더링 된 텍스트와 함께 GroupWise/Response개체를 반환

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

https://docs.djangoproject.com/ko/3.0/topics/http/shortcuts/#render

 

Django shortcut functions | Django 문서 | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 

8. 질문의 ID 가 없을 경우 Http404 예외를 발생

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

 

9. detail.html 생성

'''
polls/templates/polls/detail.html
'''

 

{{ question }}

 

10. get_object_or_404() 사용

객체가 존재하지 않을 때 get() 을 사용하여 Http404 예외를 발생

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

https://docs.djangoproject.com/ko/3.0/topics/http/shortcuts/#get-object-or-404

 

Django shortcut functions | Django 문서 | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 

 

11. detail.html 수정

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

 

12. 상세 뷰의 URL 변경

'''
polls/urls.py
'''
# URL에 'specifics' 단어 추가
path('specifics/<int:question_id>/', views.detail, name='detail'),

 

 

13. 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'),
]

 

14. index.html 수정

'''
polls/templates/polls/index.html
'''

 

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

 

https://docs.djangoproject.com/ko/3.0/intro/tutorial03/

 

첫 번째 장고 앱 작성하기, part 3 | Django 문서 | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com