Reputation: 3043
I've tried to make some global context the following way, in the pages app created a file context_processor
from pages.models import Page
def pages(request):
response = {}
response['pages'] = Page.objects.filter(visible=True, parent=None)
return response
and in settings
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
#project context processors
'pages.context_processors.pages'
],
},
},
]
on the homepage view
def home(request, template_name="home.html"):
context = RequestContext(request)
response_context = {}
...
return render_to_response(template_name, response_context)
problem is I can't access the pages data from the context, everything else works fine. If I do it directly from the views it works.
Upvotes: 1
Views: 685
Reputation: 477264
You should use the RequestContext
when you render_to_response
, as is specified in the documentation on RequestContext
:
(...) The second difference is that it automatically populates the context with a few variables, according to the engine’s context_processors configuration option.
def home(request, template_name="home.html"):
response_context = {}
# ...
return render_to_response(template_name, response_context, RequestContext(request))
But since django-2.0 render_to_response
is deprecated, and thus will be removed in django-2.2.
One typically uses render
[Django-doc] shortcut:
def home(request, template_name="home.html"):
response_context = {}
# ...
return render(request, template_name, response_context)
Upvotes: 0
Reputation: 309039
You should use render
instead of render_to_response
, and use a regular dictionary for the context.
def home(request, template_name="home.html"):
context = {}
...
return render(request, template_name, context)
The render_to_response
shortcut was deprecated in Django 2.0 and will be removed in Django 2.2. In earlier versions of Django, you could pass context_instance=RequestContext(...)
to render_to_response
if you wanted to use context processors, but this was removed in Django 1.10.
If you're following a tutorial or book that is using render_to_response
then it is out of date, and I would think about looking for a different resource.
Upvotes: 1