尝试使用request.META ['CSRF_COOKIE']时出现KeyError

时间:2020-06-09 13:03:17

标签: python django mako

我想在django2中使用mako模板,但是当我设置mako的渲染功能并尝试设置该模板以携带csrf令牌时,我发现无法在request.META中获得CSRF__COOKIE。

#coding:utf-8

from mako.lookup import TemplateLookup
from django.template import RequestContext
from django.conf import settings
from django.template.context import Context
from django.http import HttpResponse


def render_to_response(request, template, data=None):
    context_instance = RequestContext(request)
    path = settings.TEMPLATES[0]['DIRS'][0]
    lookup = TemplateLookup(
        directories=[path],
        output_encoding='utf-8',
        input_encoding='utf-8'
    )
    mako_template = lookup.get_template(template)

    if not data:
        data = {}

    if context_instance:
        context_instance.update(data)
    else:
        context_instance = Context(data)

    result = {}

    for d in context_instance:
        result.update(d)

    result['csrf_token'] = '<input type="hidden" name="csrfmiddlewaretoken" value="{0}" />'.format(request.META['CSRF_COOKIE'])
    return HttpResponse(mako_template.render(**result))

django报告错误:KeyError“ CSRF_COOKIE”,我该怎么办?

1 个答案:

答案 0 :(得分:0)

我有相同的错误,我使用此代码https://django.readthedocs.io/en/2.2.x/_modules/django/middleware/csrf.html进行了修复。

写一个if语句来判断request.META['CSRF_COOKIE']是否存在。

别忘了导入所有有用的东西:

    if 'CSRF_COOKIE' not in request.META:
        csrf_secret = _get_new_csrf_string()
        request.META['CSRF_COOKIE'] = _salt_cipher_secret(csrf_secret)
        result['csrf_token'] = ('<input type="hidden" id="django-csrf-token"'
                                ' name="csrfmiddlewaretoken" value={0}'
                                ' />'.format(request.META['CSRF_COOKIE']))

    else:
        csrf_secret = _unsalt_cipher_token(request.META["CSRF_COOKIE"])
        result['csrf_token'] = ('<input type="hidden" id="django-csrf-token"'
                                ' name="csrfmiddlewaretoken" value={0}'
                                ' />'.format(request.META['CSRF_COOKIE']))