Saturday, February 25, 2017

Re: "TemplateDoesNotExist at /"

On Sat, Feb 25, 2017 at 01:20:49PM -0800, Richard Belew wrote:
> "TemplateDoesNotExist at /"
>
> (full trace log at http://dpaste.com/3XZ8H3C)
>
> this must be near the top of django newby issues, but i'm stumped
> on the simplest example i can generate:
>
> i've used the `settings.TEMPLATES.DIRS` variable to specify a
> shared templates directory (also to simplify things), and
> am using an application's `views.py` file to anchor a
> named url, but the django engine still cannot find the `index.html` file
> i've put there.
>
> what am i missing? any hints appreciated, Rik

[...]

> TEMPLATES = [
> {
> 'BACKEND': 'django.template.backends.django.DjangoTemplates',
>
> 'DIRS': [ ( os.path.join(BASE_DIR, 'templates'), ) ],

This appears to be the incorrect line – here, you set 'DIRS' to a list
containing a single item, which is a tuple containing a path. The
problem is that you wrap the path twice. Django only expects a simple
list of paths, so if you just drop the tuple wrapping the path, you
should be fine::

'DIRS': [os.path.join(BASE_DIR, 'templates')],

> * djggApp/views.py
>
> def index(request):
> template = loader.get_template('index.html')
> context = Context({})
> return HttpResponse(template.render(context))

This is not strictly related to your problem, but I would strongly
advise not to render templates used as HTTP responses in this way.
Instead, you should be using either the render shortcut [1], or
TemplateResponse [2]. They are mostly equivalent, and both accomplish
the same thing as the above code, only with a single function call.
More often than not, less code is better.

Also, unlike TemplateResponse and render, the code above will not
apply context processors, unless you change that Context to a
RequestContext, which is something that's super easy to forget, and
I've actually seen people get bitten by that in the past, and spend a
lot of time trying to figure out why their templates are not behaving.

Cheers,

Michal

[1]: https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#render
[2]: https://docs.djangoproject.com/en/1.10/ref/template-response/#templateresponse-objects

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20170225222908.GW23772%40koniiiik.org.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment