[Django]-Django custom templatetag not getting request in context

10👍

The right way to fix this issue is to add TEMPLATE_CONTEXT_PROCESSORS += ("django.core.context_processors.request",) on your settings.py file.

Ensure to import TEMPLATE_CONTEXT_PROCESSORS first with from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS or it will not work.

1👍

Most likely the problem is you are rendering your template using regular context, that is something like this:

return render_to_response("myapp/template.html", {"some_var": a_value})

Remember that context processors are only applied to RequestContext instances. That means you have to either explicitly create a RequestContext in your render_to_response call:

return render_to_response("myapp/template.html", {"some_var": a_value},
                          context_instance=RequestContext(request))

or even better, use the new render shortcut:

return render(request, "myapp/template.html", {"some_var": a_value})

0👍

I solved it by changing

return render(request, 'myapp/mytemplate.html', {'foo':bar})

to

return render( RequestContext(request), 'myapp/mytemplate.html', {'foo':bar})

I hope this helps someone else, I wasted about 8 hours :p

0👍

I had this happen in a template.Node object in the render(). It turned out that sometimes the context had ‘request’ in it, other times it didn’t.

Like someone else suggested, RequestContext(request) is the key. My guess is that sometimes the context is called without the request being initialized like that.

I changed my function from

 def render(self, context):
      request = context['request']  # Failing here

to

 def render(self, context):
      request = RequestContext(context)['request']['request']

and it all came right.

This will force a request object in case the context object wasn’t initialized properly. For some reason I had to add [‘request’] twice, but it seems to work fine


EDIT: I spoke too soon, seems a blank context can’t be fixed. Instead you could try a workaround:

request = context.get('request')
if request is None:
    return ''

My page still seems to work fine, so I’m not exactly sure where these bad contexts are coming from.

Leave a comment