Search code examples
djangocsrf

CSRF issue on TemplateView


I have a extremely simple django TemplateView as follow:

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

And i have csrfmiddleware enabled, but why the CSRF cookie is not set on that home view? I have form rely on the csrf cookie on that page. I do not want to use {% csrf_token %} tag to do this.

I tried debug this, and found the cookie was never set because it failed the condition of CSRF_COOKIE_USED, this variable does not exist in my 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

Append my context processor settings:

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',
)

Also finding something very strange:

the csrf_cookie exists if {% csrf_token %} presents in my template.


Solution

  • If you are on 1.4, use ensure_csrf_cookie, otherwise use this javascript snippet.