我有一个非常简单的 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 存在。