Opened 6 years ago

Closed 6 years ago

#19486 closed Bug (wontfix)

csrf_token tag is empty on Resolver404 error

Reported by: SardarNL Owned by: nobody
Component: Core (Other) Version: 1.4
Severity: Normal Keywords: csrf
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


The tag {% csrf_token %} prints context.csrf_token, which is set by default django.core.context_processors.csrf, which uses django.middleware.csrf.get_token(), which looks in request.META['CSRF_COOKIE'] , which is set by CsrfViewMiddleware.process_view(). So if process_view() isn't called, then there will be no META['CSRF_COOKIE'], then {% csrf_token %} would print nothing.

Lets look now at django.core.handlers.BaseHandler.get_response(). It first calls all process_request(), then resolves the view and *then* calls all process_view(). So, if none of your URL patterns match, then your CsrfViewMiddleware.process_view() will not be called. Resolver404 exception is http.Http404, so if no view is found, the handler will use resolver.resolve404() view to serve 404 page.

The problem: 404 page uses {% csrf_token %} to render a POST form to search view. It works if URL is matched by a view, but the view itself raises Http404. It doesn't work if URL is not matched by any pattern.


1) refactor CsrfViewMiddleware.process_view(), move setting request.META['CSRF_COOKIE'] to a separate _method()
2) call this method for resolver.resolve404() view or in get_token()

Possible problems: browser may ignore cookies set by 404 page.

Workaround: search page is using csrf_exempt at this moment.

Severity: minor

Change History (1)

comment:1 Changed 6 years ago by Russell Keith-Magee

Resolution: wontfix
Status: newclosed

Context processors are not executed on error pages, so the csrf_token, and any other context request variables, aren't available. This is by design -- when errors occur, you don't want another error to be raised when showing the error page, and since context could be the cause of the error, the error pages aren't formed using a RequestContext.

Note: See TracTickets for help on using tickets.
Back to Top