파이썬 python/django

[django] django template에서 settings.py variable불러오는 방법

Aytekin 2024. 5. 9. 12:10
728x90

How to use settings.py variables in django template ? >>> Use custom_tag!

개발을 하다 보면 로컬환경, 개발환경, 배포환경 등 여러가지 환경에서 테스트해야하는 상황이 생긴다.

테스트 할때마다 각 환경에 맞는 환경설정 값을 바꾸는 건 굉장히 비효율적인 작업이고 작업 집중력도 떨어뜨리며 능률도 떨어지게 된다.

 

그래서 나 같은 경우는 secrets.json에 환경변수값들을 키값과 함께 저장해놓고 각 환경에서 secrets.json파일만 바꾸는 식으로 개발을 진행한다.

 

뭐가 되었든 각설하고 django template에서 환경에 따라 값을 다르게 넘겨줘야 하는 상황이 생기는데 이 때 settings.py에서 정의한 변수를 가져오게 된다면 문제가 간단하게 해결된다. 


 

먼저 사용하고있는 앱(INSTALLED_APPS에 등록되어 있어야 함)의 디랙토리 내에 templatetags라는 폴더를 생성하고 이 안에 __init__.py와 custom_tag.py파일을 각각 생성한다.

templatedtags안에 있는 파이썬 파일 명으로 django template에서 불러오면 된다. 예를들어 template에서 {% load custom_tag.py %}을 선언하면 template내에서 custom_tag.py를 사용할 수 있다.

 

그리고나서 custom_tag.py안에는 아래와 같이 작업해주면 된다.

from django import template
from django.conf import settings

register = template.Library()

@register.simple_tag
def get_settings(name):
    return getattr(settings, name, "")

 

그리고 사용하고자 하는 template 내에서 아래와 같이 사용 가능하다.

{% get_settings "AWS_S3_CUSTOM_DOMAIN" %}

 

나 같은 경우 settings.py에  AWS_S3관련 변수들을 아래와 같이 선언해 놓은 상태이다. 그리고 이 변수들은 노출되면 안되니깐 위에서 언급한것 처럼 secrets.json파일 안에 두고 이 파일만 잘 관리하고 있다.

# (in settings.py )
...

# SECURITY WARNING: keep the secret key used in production secret!
secret_file = os.path.join(BASE_DIR, 'secrets.json')
with open(secret_file) as f:
    secrets = json.loads(f.read())

def get_secret(setting):
    try:
        return secrets[setting]
    except KeyError:
        error_msg = "Set the {} environment variable".format(setting)
        raise ImproperlyConfigured(error_msg)
        
...

#### AWS configure ####
AWS_REGION = get_secret('AWS_REGION') #AWS서버의 지역
AWS_STORAGE_BUCKET_NAME = get_secret('AWS_STORAGE_BUCKET_NAME') #생성한 버킷 이름
AWS_ACCESS_KEY_ID = get_secret('AWS_ACCESS_KEY_ID') #액세스 키 ID
AWS_SECRET_ACCESS_KEY = get_secret('AWS_SECRET_ACCESS_KEY') #액세스 키 PW
AWS_S3_CUSTOM_DOMAIN = '%s.s3.%s.amazonaws.com' % (AWS_STORAGE_BUCKET_NAME,AWS_REGION)

...

 

 

이외에도 django에 custom-template-tags라는 기능이 있는데 이 기능을 사용하면 내가 원하는 filter나 tag를 정의해서 사용할 수 있다. 물론 django내에는 built-in 기능들이 많다. 예를들어 for문, if문도 당연히 지원하고, add같은 연산도 가능하다. 개인적으론 humanize라는 filter를 참 유용하게 사용하고 있다.


(참고) 

https://docs.djangoproject.com/en/5.0/howto/custom-template-tags/

 

How to create custom template tags and filters | Django documentation

The web framework for perfectionists with deadlines.

docs.djangoproject.com

https://stackoverflow.com/questions/433162/can-i-access-constants-in-settings-py-from-templates-in-django

 

Can I access constants in settings.py from templates in Django?

I have some stuff in settings.py that I'd like to be able to access from a template, but I can't figure out how to do it. I already tried {{CONSTANT_NAME}} but that doesn't seem to work. Is this

stackoverflow.com

 

728x90