본문 바로가기
Always Awake/Django 기본 정리(20.01.14~)

Django 공식문서 - polls 만들기 정리

by 욕심많은알파카 2020. 1. 23.

1. render과 redirect의 차이 - 참조(https://valuefactory.tistory.com/m/605?category=838937)

Django의 shortcuts 모듈에 있는 render 함수 작동 방식은 이렇다.

 

def render(request, template_name, context=None, content_type=None, status=None, using=None):
    """
    Return a HttpResponse whose content is filled with the result of calling
    django.template.loader.render_to_string() with the passed arguments.
    """
    content = loader.render_to_string(template_name, context, request, using=using)
    return HttpResponse(content, content_type, status)

 

인자들을 번역하자면 이렇다.

def render(request, 템플릿명, 템플릿 내의 변수에 대응시킬 딕셔너리, …)

 

즉, render 함수는 기본적으로는 HttpResponse 객체를 반환하는 함수인데, 템플릿을 로딩 하여 템플릿 내의 변수들을 바꿔준 뒤 내보내는 함수인것이다.

이 과정에서 템플릿 내의 변수들은 key값이 되어 세 번째 인자로 주어진 딕셔너리에서 value값을 찾아 그 값을 템플릿에 입히게 된다.

이 값들을 model에 저장해두고, view 함수 내에서 model 객체를 변수에 담아 해당 변수를 value값으로 사용하는 형식이 일반적이다.

 

 

이와 달리 같은 모듈 내의 redirect 함수의 작동 방식은 다음과 같다.

 

def redirect(to, *args, permanent=False, **kwargs):
    """
    Return an HttpResponseRedirect to the appropriate URL for the arguments
    passed.
    The arguments could be:
        * A model: the model's `get_absolute_url()` function will be called.
        * A view name, possibly with arguments: `urls.reverse()` will be used
          to reverse-resolve the name.
        * A URL, which will be used as-is for the redirect location.
    Issues a temporary redirect by default; pass permanent=True to issue a
    permanent redirect.
    """
    redirect_class = HttpResponsePermanentRedirect if permanent else HttpResponseRedirect
    return redirect_class(resolve_url(to, *args, **kwargs))

 

redirect에서 가장 중요한 인자는 첫번째 위치인자인 to이다.

to에서 특정 URL을 전달해주면, redirect는 urls.py에 있는 urlpatterns에서 해당 URL을 찾아 그에 맞는 view함수를 호출시킨다.

 

이때 to의 경로는 상대경로, 절대경로를 모두 사용할 수 있지만, 일반적으로는 urls.py에서 해당 url에 붙여진 name 문자열을 이용한다.

 

redirect를 뜯어보면 결국 HttpResponseRedirect와 resolve_url을 사용하고 있는데, resolve_url은 내부적으로 reverse함수를 사용하고 있다. 즉, reverse함수를 이용하여 인자로 주어진 to의 URL을 가져오고, 해당 URL로 HttpResponseRedirect시키는 방식이다.

 

 

정리하자면, render와 redirect의 차이점은 다음과 같다.

render : 템플릿을 로딩하여 context를 입힌 HttpResponse를 반환한다.

redirect : HttpResponse를 반환하는 다른 view를 찾아가도록 URL을 지정해주고 돌려보낸다.

 

 

 

2. generic view 중 ListView와 DetailView

generic view의 많은 항목중 ListView와 DetailView는 일반적으로 가장 자주 사용되는 뷰들이다.

 

ListView

  • 개체 목록을 표시한다. 
  • <app name>/<model name>_list.html 템플릿을 기본적으로 사용한다.이 이름과 다른 이름형식의 템플릿을 사용하고 싶다면 뷰클래스 내에서 template_name = <원하는 템플릿명> 으로 재할당해주면 된다.

DetailView 

  • 특정 개체 항목에 대한 세부 정보를 표시한다.
  • URL에 표시된 기본 키값을 pk라고 예상하기 때문에 이 뷰를 사용할 경우 키 값을 pk로 변경하면 된다.
  • <app name>/<model name>_detail.html 템플릿을 기본적으로 사용한다. 이 이름과 다른 이름형식의 템플릿을 사용하고 싶다면 뷰클래스 내에서 template_name = <원하는 템플릿명> 으로 재할당해주면 된다.

 

댓글