TemplateView上的CSRF问题

时间:2012-12-09 01:56:15

标签: django csrf

我有一个非常简单的django TemplateView如下:

class Homeview(TemplateView):
    template_name = 'home.html'

我启用了csrfmiddleware,但为什么没有在该主视图上设置CSRF cookie?我的表单依赖于该页面上的csrf cookie。我不想使用{% csrf_token %}标记来执行此操作。

我尝试对此进行调试,发现cookie从未设置过因为CSRF_COOKIE_USED条件失败,我的request.META中不存在此变量。

def process_response(self, request, response):
        if getattr(response, 'csrf_processing_done', False):
            return response

        # If CSRF_COOKIE is unset, then CsrfViewMiddleware.process_view was
        # never called, probaby because a request middleware returned a response
        # (for example, contrib.auth redirecting to a login page).
        if request.META.get("CSRF_COOKIE") is None:
            return response

        if not request.META.get("CSRF_COOKIE_USED", False):
            return response      # **It returned here, so COOKIE is never set!**

        # Set the CSRF cookie even if it's already set, so we renew
        # the expiry timer.
        response.set_cookie(settings.CSRF_COOKIE_NAME,
                            request.META["CSRF_COOKIE"],
                            max_age = 60 * 60 * 24 * 7 * 52,
                            domain=settings.CSRF_COOKIE_DOMAIN,
                            path=settings.CSRF_COOKIE_PATH,
                            secure=settings.CSRF_COOKIE_SECURE
                            )
        # Content varies with the CSRF cookie, so set the Vary header.
        patch_vary_headers(response, ('Cookie',))
        response.csrf_processing_done = True
        return response

附加我的上下文处理器设置:

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.core.context_processors.static',
    'django.core.context_processors.tz',
    'django.core.context_processors.csrf',
    'django.core.context_processors.request',
    'django.contrib.messages.context_processors.messages',
)

还找到一些非常奇怪的东西:

如果{%csrf_token%}出现在我的模板中,则存在csrf_cookie。

1 个答案:

答案 0 :(得分:1)

如果您使用的是1.4,请使用ensure_csrf_cookie,否则请使用此javascript snippet