장고 튜토리얼에 지름길이라고 적혀있는 render().
HttpResponse함수를 사용할 때 코드를 좀 더 간결하게 작성할 수 있도록 해준다.
튜토리얼대로 따라해보면 render를 사용하는 경우,
def index(request) :
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('mydjango/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
위의 코드가 아래의 코드로 대체가능하다.
template 한줄이 빠졌고, return 함수 모양이 좀 더 심플해졌다.
def index(request) :
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {
'latest_question_list': latest_question_list,
}
return render(request, 'mydjango/index.html', context)
render를 모든 view에 적용한다면 loader와 HttpResponse를 사용하지 않으므로 import하지 않아도 된다.
from django.shortcuts import render 를 해준다.
render(request, template, dict형태의 context 데이터)
세번째 인자는 optional.
다음으로, HTTP 404 error리턴해주기.
HTTP 404 error는 not found 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, 'mydjango/detail.html', {'question': question})
#return HttpResponse("You're looking at question %s." % question_id)
기존의 HttpResponse를 주석처리하고 try except 구문을 추가해준다.
Question을 못찾는 경우 exception 처리에서 Http404 error를 발생시키도록 한다.
이렇게 나온다.
여기서 또 지름길..?
from django.shortcuts import get_object_or_404, render
def detail(request, question_id):
"""
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist...!!")
"""
question = get_object_or_404(Question, pk=question_id)
return render(request, 'mydjango/detail.html', {'question': question})
#return HttpResponse("You're looking at question %s." % question_id)
기존의 코드들을 주석처리했다.
try except구문을 get_object_or_404 함수로 대체가능하다.
함수 이름부터 직관적으로 object를 못가져오면 404를 발생시키라고 되어있다.
비슷한 함수로 get_list_or_404 가 있다. 얘는 list를 가져오지 못하면 404error를 발생시켜준다.
이런식으로 코드를 간결하게 구현할 수 있는 지름길 함수가 더 많이 있을것 같다.
잘 활용해보자.
'개발Study > web' 카테고리의 다른 글
Django와 bootstrap (0) | 2020.11.29 |
---|---|
Django template (0) | 2020.11.22 |
Django admin 비밀번호 분실했을 때 (0) | 2020.11.15 |
Django view 추가하기 + Template (0) | 2020.10.25 |
Django 관리자 (0) | 2020.10.25 |
댓글