【问题标题】:Django 1.8 - KeyError 'request'Django 1.8 - KeyError '请求'
【发布时间】:2015-05-31 18:59:18
【问题描述】:

我有点傻眼了,希望有人能理解这个问题!

这是上下文:

{'form': <LoginForm bound=False, valid=Unknown, fields=(password;remember;login)>,
 'redirect_field_name': 'next',
 'redirect_field_value': None,
 'signup_url': u'/accounts/signup/',
 'site': <Site: brilliantactor.com>,
 u'view': <allauth.account.views.LoginView object at 0x10d7dead0>}

请求对象看起来很正常

'<WSGIRequest\npath:/accounts/login/,\nGET:<QueryDict: {}>,\nPOST:<QueryDict: {}>,\nCOOKIES:{\'_ga\': \'GA1.1.908939259.1424705622\',\n \'csrftoken\': \'Ga0urMmd7AgBouS9KeH5V4EQNoyE8cqU\',\n [...]

但是当读取以下行时:

context = make_context(context, request)

输出上下文如下

[{'False': False, 'None': None, 'True': True}, 
 {}, 
 {'form': <LoginForm bound=False, valid=Unknown, fields=(password;remember;login)>, 
  'redirect_field_value': None, 
  'redirect_field_name': 'next', 
  'signup_url': u'/accounts/signup/', 
  'site': <Site: brilliantactor.com>, 
  u'view': <allauth.account.views.LoginView object at 0x10d7dead0>}]

由于新的上下文对象没有“请求”键,一些模板标签会失败,例如django-allauth


以下是失败的示例:

https://github.com/pennersr/django-allauth/blob/master/allauth/socialaccount/templatetags/socialaccount.py#L20


我的 TEMPLATE_CONTEXT_PROCESSORS:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            join(BASE_DIR, 'templates'),
            # insert your TEMPLATE_DIRS here
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
                # list if you haven't customized them:
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                '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',

                "allauth.account.context_processors.account",
                "allauth.socialaccount.context_processors.socialaccount",
            ],
        },
    },
]

有人见过吗?

【问题讨论】:

  • TEMPLATE_CONTEXT_PROCESSORS 设置中有什么?
  • @alecxe 感谢您的回复。我已将上下文处理器附加到问题中:)

标签: python django django-templates django-allauth django-1.8


【解决方案1】:

对于 1.8,添加

'django.template.context_processors.request',

而不是

'django.core.context_processors.request',

【讨论】:

    【解决方案2】:

    正如 Alex 所暗示的,您需要添加 request 上下文处理器;默认情况下不激活。

    'django.core.context_processors.request',
    

    【讨论】:

    • 对于 >=1.8 添加 'django.template.context_processors.request' 代替。
    猜你喜欢
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2021-11-22
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多