Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The context_instance argument of render_to_string is deprecated

Tags:

django

I'm using Django 1.9.

With render_to_string I can easily pass rendered html as json to my clientside script. However, since the template rely on variables such as user, I need to also pass the context_instance=RequestContext(request), otherwise the template will not know what request.user is, so if statements break, etc.

However I am getting this deprecation warning:

RemovedInDjango110Warning: The context_instance argument of render_to_string is deprecated. response_data['content'] = render_to_string("profile/userprofile_detail/content.html", context, context_instance=RequestContext(request))

What is the non-deprecated way to pass RequestContext in a render_to_string?

like image 740
Sebastian Olsen Avatar asked Apr 07 '16 22:04

Sebastian Olsen


2 Answers

render_to_string has a context argument, so you can just pass it directly as a dictionary as you would with any other response

render_to_string(template_name, context=None, 
                 context_instance=_context_instance_undefined, request=None, using=None)

The linked documentation also includes a note encouraging this

Deprecated since version 1.8:

The context_instance argument is deprecated. Use context and if needed request.

like image 75
Sayse Avatar answered Sep 18 '22 20:09

Sayse


The recommended method is to pass request when you call render_to_string. Django will then render the template with a request context.

render_to_string("profile/userprofile_detail/content.html", context, request=request)
like image 20
Alasdair Avatar answered Sep 19 '22 20:09

Alasdair