3
votes

I understand things have changed in Django 1.8 with how render_to_response takes arguments. I have lots of views and use this pattern everywhere:

...return render_to_response( template, context, context_instance=MyRequestContext(request))

MyRequestContext extends the RequestContext and adds some paramaters I always use in my templates.

Now this no longer works, and values in MyRequestContext is no longer accessible in the templates anymore.

So how should RequestContext be use now in Django 1.8? I need them + some context passed to all my templates.

/ J

-- EDIT --

Thanks for all the answers, as you point out this should work...

I ended up rewriting and replacing my previous subclassing of RequestContext --> MyRequestContext w. doing a separate ContextProcessors function and adding this into my OPTIONS:context_processors list and then using a normal RequestContext(request) in all of my views. Not sure what bug/problem I had in old solutions but this works now. Again - thanks for inspiration and responses.

2
According to the docs context_instance is deprecated since 1.8. It's now just context.rfkortekaas
context_instance is only deprecated in 1.8, you can still use render_to_response the way you are doing until you upgrade to Django 2.0.Alasdair

2 Answers

0
votes

You can manually fetch the template and render it to a HttpResponse object:

from django.template.loader import get_template
from django.http import HttpResponse

template = get_template(template_name)
context = MyRequestContext(request, context_dict)
return HttpResponse(template.render(context))
0
votes

I bumped into this as well and had to read the docs on render_to_response a couple of times.

The thing that confused me is the example code in combination with the deprecation warning:

return render_to_response('my_template.html',
    my_context,
    context_instance=RequestContext(request))

Deprecated since version 1.8: The context_instance argument is deprecated. Simply use context.

Note that context_instance is still used at many examples in the documentation and it is okay to use it that way until Django 2. I don't want to wait until I'm forced to change when I upgrade so...

I moved my_context dict out of render_to_response into the RequestContext class. I believe this must be the new style:

return render_to_response('template.html', 
    context=RequestContext(request, my_context))

Context is the second argument, so you don't even have to name it:

return render_to_response('template.html', 
     RequestContext(request, my_context))