IT TIP

장고에서 나만의 컨텍스트 프로세서 만들기

itqueen 2020. 10. 19. 13:46
반응형

장고에서 나만의 컨텍스트 프로세서 만들기


모든 뷰 (대부분 사용자 지정 인증 유형 변수)에 특정 변수를 전달해야하는 시점에 도달했습니다.

내 컨텍스트 프로세서를 작성하는 것이이를 수행하는 가장 좋은 방법이라고 들었지만 몇 가지 문제가 있습니다.

내 설정 파일은 다음과 같습니다.

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.contrib.messages.context_processors.messages",
    "sandbox.context_processors.say_hello", 
)

보시다시피 'context_processors'라는 모듈과 'say_hello'라는 함수가 있습니다.

어떤 모습

def say_hello(request):
        return {
            'say_hello':"Hello",
        }

이제 내 관점에서 다음을 수행 할 수 있다고 가정하는 것이 옳습니까?

{{ say_hello }}

지금은 내 템플릿에서 아무것도 렌더링되지 않습니다.

내 견해는

from django.shortcuts import render_to_response

def test(request):
        return render_to_response("test.html")

작성한 컨텍스트 프로세서가 작동해야합니다. 문제는 당신의 관점에 있습니다.

당신의 관점이 렌더되고 있다고 확신 RequestContext합니까?

예를 들면 :

def test_view(request):
    return render_to_response('template.html')

위의보기는에 나열된 컨텍스트 프로세서를 사용하지 않습니다 TEMPLATE_CONTEXT_PROCESSORS. 다음 RequestContext과 같이 제공하는지 확인하십시오 .

def test_view(request):
    return render_to_response('template.html', context_instance=RequestContext(request))

django 문서 에 따르면 rendercontext_instance 인수를 사용하여 render_to_response 대신 바로 가기로 사용할 수 있습니다 .

또는 render()RequestContext 사용을 강제하는 context_instance 인수를 사용하여 render_to_response () 호출과 동일한 바로 가기를 사용하십시오 .


Django 1.8부터 다음과 같이 사용자 정의 컨텍스트 프로세서를 등록합니다.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            'templates'
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'www.context_processors.instance',
            ],
        },
    },
]

컨텍스트 프로세서가 앱 www있다고 가정합니다 .context_processors.py


If you’re using Django’s render_to_response() shortcut to populate a template with the contents of a dictionary, your template will be passed a Context instance by default (not a RequestContext). To use a RequestContext in your template rendering, use the render() shortcut which is the same as a call to render_to_response() with a context_instance argument that forces the use of a RequestContext.

참고URL : https://stackoverflow.com/questions/2893724/creating-my-own-context-processor-in-django

반응형