backend/Django&Python

[Django] View단 연결하기

findTheValue 2021. 8. 25. 02:52

얘는 좀 더 정리할 예정.


첫 번째 장고 앱 작성하기, part 3

  • view는 장고가 일반적으로 특정 기능과 템플릿을 제공하는 웹 페이지의 종류.

  • 요청된 페이지의 내용이 담긴 HttpResponse의 반환
  • Http404같은 예외 발생
  • 둘 중 하나를 하도록 설계.
# from django import template
from django.http import HttpResponse
# from django.template import loader
# 숏컷으로 render 사용. template에 context를 채워넣어 표현한 경과를 HttpResponse객체와 함꼐 돌려주는 구문. render
from django.shortcuts import render,get_object_or_404
from django.http import Http404

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)

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))
    return render(request, 'polls/index.html',context)

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

def results(request, question_id):
    response = f"I'm the results of question {question_id}"
    return HttpResponse(response)

def vote(request, question_id):
    return HttpResponse(f"You vote this Q {question_id}")

URLS

  • 라우팅.
  • namespace : app_name을 추가해 각각의 App들을 구별하기 위함.
  • html url을 app_name을 통한 id를 달아줘 라우팅함.
from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', 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'),

]

템플릿

image-20210825022540608

네임 스페이싱을 통해 올바른 경로를 가리키도록 하기 위함.

Shortcut

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