📢 공지사항
////////
home

장고 view사용 ,html불러오기 및 연결의 사본

뷰=장고웹로직을 관리
[생성]
색인
세부
결과
투표기능
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)
Python
복사
클라이언트 request→ response
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'), ]
Python
복사
polls/urls.py수정
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)
Python
복사
question데이터에서 5개까지 가져오기
polls안에 templates에 해당 디렉토리 명으로 폴더 만들어서 관리 =장고멍청이
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 %}
Python
복사
views.py업데이트
from django import template 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))
Python
복사
httpresponse대신 render()함수 사용가능
return HttpResponse(template.render(context,request))
Python
복사
return render(request, 'polls/index.html', context)
Python
복사
404에러
detail함수 수정
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})
Python
복사
get_object_or_404 import → try except없이 사용가능
def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question})
Python
복사