Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between render & render_to_string?

Tags:

python

django

Currently I have referencing some old project created in django 1.9 version of my company and I have found that they have used render_to_string function many times as of now I am using render function but I have never used render_to_string.

Example code of render_to_string function is as below.

return HttpResponse(render_to_string('sales/sale.html', {'sale_id' : sale_id, `unique_number`:uni_id}, RequestContext(request))) 

I have tried to search online find answer but not able to find any perfect answer.

What is difference between both these function & how they behave ?

When to decide which function is best suitable to use in project ?

Thanks.

like image 249
Moon Avatar asked Oct 15 '22 08:10

Moon


1 Answers

We can check the source code of render [GitHub]:

def render(request, template_name, context=None, content_type=None, status=None, using=None):
    """
    Return a HttpResponse whose content is filled with the result of calling
    django.template.loader.render_to_string() with the passed arguments.
    """
    content = loader.render_to_string(template_name, context, request, using=using)
    return HttpResponse(content, content_type, status)

In essence render thus calls render_to_string(..) with the template_name, context, request, and using as parameters, and then constructs a HttpResponse with that result and optionally a content_type and status. It is thus a shortcut that combines the two.

like image 161
Willem Van Onsem Avatar answered Oct 20 '22 11:10

Willem Van Onsem