이마닷의 블로그

[django] 템플릿에서 context object의 메소드 사용하기 본문

python

[django] 템플릿에서 context object의 메소드 사용하기

움나나움 2020. 1. 15. 19:05

django의 View에서는 Template에서 사용될 context 변수들과 함께 해당 웹 페이지를 띄우게 되고, template에서는 이러한 context들을 웹 페이지 내에 적절히 배치함으로써 웹 페이지를 작성한다. 일반적으로 context 변수들은 object 형태로 주어지게 되는데, 각각의 object는 각각의 Model(class)에 속하게 되므로, 해당 인스턴스에서 클래스 메소드들을 사용할 수 있다. 이를 위해 해주어야 할 작업에 대해 알아보고자 한다.

1. Python의 decorator 기능

def example_decorator(func):
    def decorated():
        print("decorated!")
        func()
    return decorated

class ExampleDecorator:
    def __init__(self,f):
        self.func = f

    def __call__(self,*args,**kwargs):
        print("decorated!")
        self.func(*args,**kwargs)

@example_decorator
# 또는
@ExampleDecorator
def func():
    pass

사실 여태까지 django 공부를 하면서 @decorator를 봐도 그냥 함수를 꾸며주는 거구나 하고 그냥 넘어갔었는데, 아래 블로그를 보고 개념이 좀 정리가 되었다.

요약해서 말하자면 파이썬의 decorator란 어떤 함수 위에 붙여 씀으로써, 데코레이터 아래에 있는 함수의 코드를 데코레이터의 코드와 합쳐주는 것이다. 보통 데코레이터 코드에서 수행하는 반복 작업을 없애주기 위해 사용한다. template에서 메소드를 사용하기 위해서는, 각 모델 클래스에서 메소드를 정의할 경우에 각각 필요한 데코레이터를 달아줘야 한다.

 

2. 변수가 없는 메소드

class Post(models.Model):

    ...

    @property
    def update_counter(self):
        self.post_hit = self.post_hit + 1
        self.save()
<div>
    <h4>Contents</h4>
    {{ post.update_counter }}
    {{ post.post_contents}}
</div>

파라미터가 없는 단순 메소드의 경우, 위의 코드와 같이 @property 데코레이터를 달아주면 된다. 이 경우 template에서 별다른 추가 작업 없이, context로 넘어간 해당 변수를 통해 해당 메소드를 참조해주기만 하면 된다.

 

3. 변수가 있고 반환값이 있는 메소드

from django import template

register = template.Library()

class Post(models.Model):
	
    ...
    
    @register.filter(name='update_counter')
    def update_counter (self, delta):
    	self.counter += delta
        self.save()
        return self.counter
    
<div>
    <h4>Contents</h4>
    {{ post|update_counter:1 }}
    {{ post.post_contents }}
</div>

파라미터가 있는 메소드의 경우, 위의 코드와 같이 register를 데코레이터로 사용해 해당 메소드를 filter로 등록하는 방법을 사용한다. 이 경우 기존 object의 프로퍼티에 filter를 씌우는 형식으로 이루어진다. 위 예제에서 update_counter는 post의 counter 프로퍼티를 updae_counter를 1로 증가시켜주고, 이를 다시 반환해주는 역할을 한다. 즉, python 코드에서의 self, delta에 post와 1이 대입되는 것이다.

 

[참고] https://bluese05.tistory.com/30

[참고] https://code1018.tistory.com/248

[참고] http://blog.naver.com/PostView.nhn?blogId=agney&logNo=60184520189

[참고] http://www.pfinn.net/custom-django-filter-tutorial.html

'python' 카테고리의 다른 글

[django] MySQL과 연동하기  (0) 2019.09.29
[django] 가장 기본적인 CBV(generic view)  (0) 2019.09.22
Comments