본문 바로가기

장고(DJango)

get_context_data()

ContextMixin 클래스에 정의되어 있는 함수이다.

 

CBV를 작성할때, 만약 HTML 문서로 보내고 싶은 객체가 존재할 경우 이용한다.

 

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['number'] = random.randrange(1, 100)
    return context

 

위의 메서드를 재정의(오버라이딩) 하게 되면 number 라는 이름을 갖는 객체가 추가되어 전달된다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>hello world!</h1>
<div>{{ number }}</div>
</body>
</html>

위와같이 사용이 가능하다.


결과 화면