The Man
The Man

Reputation: 435

Why does Django need a request object in rendering a template?

Why does Django need a request object in rendering a template?

 return render(request, 'polls/index.html', context)

Upvotes: 5

Views: 1780

Answers (3)

Seb D.
Seb D.

Reputation: 5195

As per the docs about render:

Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text.

Thus it's meant to be used in views, where you have a request object and need to return an HttpResponse. A typical use case is when you build the context from the request.

If you only need to render a template, you can use the shortcut function render_to_string:

from django.template.loader import render_to_string

render_to_string('your_template.html', {'some_key':'some_value'})

Or do it manually:

from django.template import Context, Template 

Template('your_template.html').render(Context({'some_key':'some_value'})

Upvotes: 5

n.abing
n.abing

Reputation: 585

The request argument is used if you want to use a RequestContext which is usually the case when you want to use template context processors. You can pass in None as the request argument if you want and you will get a regular Context object in your template.

Upvotes: 2

dhui
dhui

Reputation: 522

I believe this is b/c the render() shortcut is using a RequestContext

You could also use get_template directly and call render with a normal Context

Upvotes: 1

Related Questions