这是我在模板标签中的代码
httr
在模板中,它用作library(httr)
set_config(use_proxy(url="http://proxy.mycompanyname.com", port=****))
,问题是@register.simple_tag(takes_context=True, name=CAR_TEMPLATE_TAG_NAME)
def g_c(context,session_key=None,c_class=Car):
request = context['request']
return c_class(request, session_key=session_key)
处的keyerror'request'
这是我的模板上下文,
{% g_c as car %}
这是尝试,
这是templatetag中添加的新行
request = context['request']
已添加设置
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
# 'django.core .context_processors.request,
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
答案 0 :(得分:0)
您必须先导入设置:
from django.conf.settings import TEMPLATE_CONTEXT_PROCESSORS
答案 1 :(得分:0)
默认设置包括请求模板上下文处理器,该处理器添加了要在模板中使用的请求。
https://docs.djangoproject.com/en/2.2/topics/templates/#configuration https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/#simple-tags
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.tz',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
访问上下文
DEFAULT_C_CLASS = Car
@register.simple_tag(name=CAR_TEMPLATE_TAG_NAME, takes_context=True)
def g_c(context, session_key=None, c_class=None):
request = context['request']
c_class = c_class or DEFAULT_C_CLASS
session_key = session_key or request.session.session_key
# Note this class __init__ should return a fragment.
return c_class(request, session_key=session_key)
base.html
{% load my_custom_tag %}
{% g_c as car %}
您还可以直接在模板中传递请求对象
@register.simple_tag(name='g_c')
def g_c(request, session_key=None, c_class=None):
c_class = c_class or DEFAULT_C_CLASS
session_key = session_key or request.session.session_key
# Note this class __init__ should return a fragment.
return c_class(request, session_key=session_key)
base.html
{% load my_custom_tag %}
{% g_c request as car %}