Django Context处理器没有Django的其余部分?

时间:2017-05-25 19:31:19

标签: python django

我尝试将Django模板用作独立应用程序,但我遇到了Engine.context_processors

的问题

我的主要文件是:

from django.template import Template, Context, Engine

template_content = """ -- HEADER ---
{{ var|star_wrap }}
{% fullpath "filename_123.txt" %}
{{ abc }}
 -- FOOTER ---"""

data = {'var': 'Ricardo'}

engine = Engine(
    debug=True,
    builtins=['filters'],
    context_processors=(
        'context_processors.my_context_processor'
    )
)    
template = Template(
    template_content,
    engine=engine,
)
context = Context(data)    
result = template.render(context)

filters.py我有:

from django import template

# --- Filters
register = template.Library()  # pylint: disable=C0103

@register.filter(name='star_wrap')
def star_wrap(value):
    return "** " + value + " **"

@register.simple_tag(takes_context=True)
def fullpath(context, arg):
    print(context)
    return "/tmp/"+str(arg)

context_processors.py我有:

def my_context_processor(request):
    return {'abc': 'def'}

基本上我的my_context_processor中的数据会被忽略...... {{ abc }}没有被替换。请参阅上面代码的输出。我也打印上下文:

[{'False': False, 'None': None, 'True': True}, {'var': 'Ricardo'}]
 -- HEADER ---
** Ricardo **
/tmp/filename_123.txt

 -- FOOTER ---

知道为什么my_context_processor被忽略了吗?

1 个答案:

答案 0 :(得分:0)

答案是:使用RequestContext代替Context ...