[Fixed]-Django – Why does context.get('request') return a None value?

1👍

The request and other values from context processors are missing from the context.

The request is still available as an attribute on the RequestContext. You can access it with context.request.

👤knbk

0👍

Context processors run immediately before the template is rendered, i.e. are not accessible from where you’re running that code. Pass the context to a template and print {{ request }} somewhere and you will see the HttpRequest object.

https://docs.djangoproject.com/en/1.8/ref/templates/api/#

For what it’s worth – if you’re trying to get the request object, it’s the first argument passed to pretty much every view. You can access it and share it there. If you’re strictly trying to get access to it in a template, try accessing it like I mentioned above and see if you can get to it.

https://docs.djangoproject.com/en/1.8/topics/http/views/

0👍

Complementing @Mothbawls answer, if you need pre_process the request or context_data, you could use a request_process or a process_template_response middleware.

👤Gocht

0👍

Also complementing @Mothbawls answers, for CBV’s, I use the following Mixin to pass in the request to the template context:

class RequestMixin(object):
    """ Generic mixin to pass request data into context. """
    def get_context_data(self, **kwargs):
        context = super(RequestMixin, self).get_context_data(**kwargs)
        context['request'] = self.request
        return context

Leave a comment