Harton Harton - 1 month ago 7
Python Question

Django can't quite get the right path

I have this view here:

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.template import loader
from django.views.generic import ListView

class IndexView(ListView):
def get(self, request):
template_name = loader.get_template('home/blog.html')
return render(request, template_name)
return HttpResponse(template_name.render(request))


So if I remove return render(request, template_name) everything will be working properly but now when I trying to use return render(request, template_name) I get these error:

<django.template.backends.django.Template object at 0x7f13916f46d8>


places where Django tried to find the template:

django.template.loaders.app_directories.Loader: /home/marton/documents/github/fmi-fall-2016/django/click_bait/miranda/home/templates/<django.template.backends.django.Template object at 0x7f13916f46d8> (Source does not exist)
django.template.loaders.app_directories.Loader: /home/marton/documents/github/fmi-fall-2016/django/click_bait/env/lib/python3.4/site-packages/django/contrib/admin/templates/<django.template.backends.django.Template object at 0x7f13916f46d8> (Source does not exist)
django.template.loaders.app_directories.Loader: /home/marton/documents/github/fmi-fall-2016/django/click_bait/env/lib/python3.4/site-packages/django/contrib/auth/templates/<django.template.backends.django.Template object at 0x7f13916f46d8> (Source does not exist)


What should I do? Now is the time to say that eversince I have started this project I have had problem with paths, half an hour ago for some reason Django was searching in my virtual environment's folder.

Answer

You are misunderstanding a few things here. The loader returns a template object, not a template name. You don't need that call to loader.get_template at all; you pass the template path directly to render:

 return render(request, 'home/blog.html')