Templatedoesnotexist at django как исправить

Fixing TemplateDoesNotExist Django error Django is a popular Python web framework. Because it is popular, a lot of people are learning Django. And if you’ve just started learning Django and are stuck with TemplateDoesNotExist error, see the solution in this article. “TemplateDoesNotExist at /” error So, when developing your Python Django web application, you […]

Содержание

  1. Fixing TemplateDoesNotExist Django error
  2. “TemplateDoesNotExist at /” error
  3. Fix #1: add templates
  4. Fix #2: check settings, route URLs, write views
  5. Fix #3: specify templates directory in settings
  6. Conclusion
  7. Forums
  8. TemplateDoesNotExist

Fixing TemplateDoesNotExist Django error

Django is a popular Python web framework. Because it is popular, a lot of people are learning Django. And if you’ve just started learning Django and are stuck with TemplateDoesNotExist error, see the solution in this article.

“TemplateDoesNotExist at /” error

So, when developing your Python Django web application, you can encounter the following error:

The error has long traceback next to it. This error means that Django framework cannot find a template for requested URL. If you already have your templates/ and views.py trying to render them, go ahead to Fix #3. There are few possible reasons Django can issue that error. Let’s consider them below.

Fix #1: add templates

Make sure you add actual templates to your templates folder. If you don’t have any templates, create templates in the base directory of your website and add a template (for example, index.html ). I will assume your app is named “app” and the project name is “website”. The structure of your project will look like this:

Fix #2: check settings, route URLs, write views

  1. Go to website/settings.py and check if your app is present in INSTALLED_APPS list. If not, add it and run python3 manage.py makemigrations; python3 manage.py migrate .
  2. Go to website/urls.py and make sure it has path(», include(‘app.urls’)), line in the urlpatterns array.
  3. Check if app/urls.py has line from . import views at the top and path(», views.index, name=’index’), in the urlpatterns array.
  4. Go to app/views.py and ensure it has index function which serves the index page. If not, write this to your app/views.py :

Next, restart your web server and check if error is gone. If not, try Fix #3.

Fix #3: specify templates directory in settings

Go to your main website/settings.py file and find the TEMPLATES array.

Add ‘DIRS’: [ BASE_DIR / ‘templates’ ], line to make the array look like this:

If you are wondering, “/” (slash) operator from pathlib module concatenates two Path objects properly. After the third fix, your app should finally work.

Conclusion

To recap, when you encounter TemplateDoesNotExist in Django application, you should do the following things to fix it:

Источник

Forums

TemplateDoesNotExist

Trying to launch my first web app on PA and things just aren’t working when going from local to PA for some reason.

My Template path is settings.py is

and my app is included in the installed_apps section of settings.py. How do I fix this?

If you go to the web page, you can see some stuff that’s there to help you debug stuff like this. Just underneath the error you quote, there’s this bit:

So, Django is telling you exactly where it looked for your template Kappa/index.html . The first one is the place it looked based on the TEMPLATE_PATH you set — it’s looking for the file inside /home/KTruong88/Kappa_Ranks/templates/ . The next two attempts were looking inside your installed Django apps. It only lists two, the standard Django admin and Django auth apps. So if your template file is inside the template subdirectory of one of your own apps, then that suggests that your app isn’t on the INSTALLED_APPS list in your Django settings.

I still don’t get what I’m supposed to change here. When I look at /home/KTruong88/Kappa_Ranks/templates/Kappa folder, I see index.html clearly there. I check my settings.py file too and it definitely is in the installed apps section too at /home/KTruong88/Kappa_Ranks/Kappa_Ranks/settings.py.

I also edited my static files section with /templates/ as url and the path as /home/KTruong88/Kappa_Ranks/templates.

Perhaps it’s a case problem? On PythonAnywhere (like most Unix-based environments) directory names are case sensitive; if your local setup is on Windows or another case-insensitive OS then things would work there but wouldn’t here.

So, for example, if your template is in /home/KTruong88/Kappa_Ranks/templates/kappa rather than /home/KTruong88/Kappa_Ranks/templates/Kappa then the template could be found on Windows, but not on Unix.

If you’re sure that’s not the problem, can I take a look at your code? We can see it from our side but we always ask permission first.

I would love for you to take a look at my code. I did a double check and I’ve kept my project names and app names capitalized and I don’t remember changing any names/capitalizations when I cloned it from github either.

It’s the case of the templates directory inside /home/KTruong88/Kappa_Ranks/ — it’s called Templates with a capital T, not templates . If you rename it then it should all work fine.

The complicated thing is going to be fixing that in Git, which can be a bit awkward when you want to change the case of a directory name. I’ve found the best way is to do it as two separate checkins; firstly git mv the «Templates» directory to something like «temp-templates», commit that, and then git mv «temp-templates» to «templates», then commit that.

My heart just skipped. It works. Thanks for the help, I found out the templates was supposed to be capitalized.

Edit: sorry, should have triple checked before posting again. Will definitely fix the git thing too right now

Excellent, glad I could help!

Hello, I am getting the same problem, but can not work out with the solution. Can you help me?

Can you provide a bit more information?

Sorry. I just deleted the whole app and restarted with the tutorial again.

Here it is (again):

Template-loader postmortem Django tried loading these templates, in this order:

Using engine django:

(Source does not exist) django.template.loaders.app_directories.Loader: /home/khizirsiddiqui/my-first-blog/myvenv/lib/python3.5/site-packages/django/contrib/auth/templates/blogpost_list.html (Source does not exist)

But my template is in my-first-blog/blog/.

That’s a strange path. Could one of your settings.py entries for the template config be missing a comma between two strings in a list?

It is working on my Windows

PythonAnywhere is not running on Windows. Your paths need to be valid Linux paths and a backslash is not valid (Linux uses forward slashes as path separators). My guess is you’ve got a Windows-y path in your settings somewhere.

How do I search that ‘Windows-y’?

Thanks, it is now working with the forward slash

Excellent, thanks for confirming!

How should I put the path for my templates in settings.py, should it must be a direct path or the virtualenv path. Could you please give an example.

the direct path, not the virtualenv path.

99% of the time you shouldn’t need to add any template paths to settings.py. if you just keep your templates in a folder called «templates» inside one of your own apps (and it’s in INSTALLED_APPS), then django will find it automatically.

I am new to the python anywhere and i’m getting below exception,

Here is the location=(«Exception Location:/home/Kishor123/.virtualenvs/myenv/lib/python3.8/site-
packages/django/template/loader.py in get_template, line 19″)

Could you please assist me here?

You do not have a template with the filename that you are trying to use in any of the places that you have told Django to look for templates. The exception page that Django generates has additional information that you can use to debug. First, in the «Exception value» field at the top, it will tell you the name of the template that it’s looking for. Second, in the «template loader postmortem» section, it will show you which directory it looked in to find the template. If you do not have a template file with the correct name in any of the listed directories, then Django cannot find your template.

It works and my website is working fine now. Thanks for your help!

Great! Glad to help.

Hello. Same is here.

I dont get it. I have a several templates in same directory. Some of them is work fine, some (like this one) — no. Can u help me please?

[edit by admin: formatting]

If you look at the error message on your site, in the stack trace you will see this:

Note that there is a space in between the template name and the close quote. This means that Django will be looking for a template file with a space at the end, and your file (I assume) doesn’t have a space at the end of its name.

If you fix your extends statement so that it doesn’t have that extra space, it should work fine. Don’t forget to reload the website on the «Web» page after making the fix.

Omg, its all working now, what a noob i am. Thank you, God

Glad we could get a solution for you 🙂

I’m trying to deploy my first Django project on pythonanywhere but facing a problem to load base.html.

this error is displaying:

[edit by admin: formatting]

Where have you stored your file base.html ?

see your url.py and or your views.py check the path of ur index.html. if it is under templates folder template_name= index.html but if it is under your app or under another folder u need to specify the correct path for the template template_name= whatever_your _folder_is/index.html

I’m trying to deploy my first Django project on pythonanywhere but facing a problem to load base.html.

this error is displaying: Django Version: 3.0.8 Python Version: 3.6.9 Installed Applications: [‘django.contrib.admin’, ‘django.contrib.auth’, ‘django.contrib.contenttypes’, ‘django.contrib.sessions’, ‘django.contrib.messages’, ‘django.contrib.staticfiles’, ‘first_app’] Installed Middleware: [‘django.middleware.security.SecurityMiddleware’, ‘django.contrib.sessions.middleware.SessionMiddleware’, ‘django.middleware.common.CommonMiddleware’, ‘django.middleware.csrf.CsrfViewMiddleware’, ‘django.contrib.auth.middleware.AuthenticationMiddleware’, ‘django.contrib.messages.middleware.MessageMiddleware’, ‘django.middleware.clickjacking.XFrameOptionsMiddleware’]

Template loader postmortem Django tried loading these templates, in this order:

Using engine django: * django.template.loaders.filesystem.Loader: /home/Ameeru/django-deployment-example/first_level/template/basic_appindex.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/Ameeru/.virtualenvs/django3/lib/python3.6/site-packages/django/contrib/admin/templates/basic_appindex.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/Ameeru/.virtualenvs/django3/lib/python3.6/site-packages/django/contrib/auth/templates/basic_appindex.html (Source does not exist)

Traceback (most recent call last): File «/home/Ameeru/.virtualenvs/django3/lib/python3.6/site-packages/django/core/handlers/exception.py», line 34, in inner response = get_response(request) File «/home/Ameeru/.virtualenvs/django3/lib/python3.6/site-packages/django/core/handlers/base.py», line 115, in _get_response response = self.process_exception_by_middleware(e, request) File «/home/Ameeru/.virtualenvs/django3/lib/python3.6/site-packages/django/core/handlers/base.py», line 113, in _get_response response = wrapped_callback(request, callback_args, *callback_kwargs) File «/home/Ameeru/django-deployment-example/first_level/first_app/views.py», line 8, in index return render(request,’basic_appindex.html’,<‘name’:’user,Welcome you’>) File «/home/Ameeru/.virtualenvs/django3/lib/python3.6/site-packages/django/shortcuts.py», line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File «/home/Ameeru/.virtualenvs/django3/lib/python3.6/site-packages/django/template/loader.py», line 61, in render_to_string template = get_template(template_name, using=using) File «/home/Ameeru/.virtualenvs/django3/lib/python3.6/site-packages/django/template/loader.py», line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain)

Exception Type: TemplateDoesNotExist at / Exception Value: basic_appindex.html

It looks like you’re using a backslash ( ) somewhere in your code, where you should be using a forward slash ( / ).

You all are great with support, I really appreciate it. I’m also having a TemplateDoesNotExist error on a django 3.1.1 site and I would appreciate your advice. My traceback is here.

It seems like the problem is that my template directory isn’t being loaded but I can’t figure out why:

The parts I think are relevant in settings.py include:

The home page pattern in urls.py is below, and I do get to the correct template when I access home:

If I activate my virtual environment, run shell_plus. and import settings, it works fine with no traceback.

Could you copy/paste the traceback here in the forums? That link doesn’t work for me for some reason.

Happy to, Giles! Thanks.

Request Method: GET Request URL: http://robline.pythonanywhere.com/

Django Version: 3.1.1 Python Version: 3.6.9 Installed Applications: [‘django.contrib.admin’, ‘django.contrib.auth’, ‘django.contrib.contenttypes’, ‘django.contrib.sessions’, ‘django.contrib.messages’, ‘django.contrib.staticfiles’, ‘django_extensions’, ‘pep’] Installed Middleware: [‘django.middleware.security.SecurityMiddleware’, ‘django.contrib.sessions.middleware.SessionMiddleware’, ‘django.middleware.common.CommonMiddleware’, ‘django.middleware.csrf.CsrfViewMiddleware’, ‘django.contrib.auth.middleware.AuthenticationMiddleware’, ‘django.contrib.messages.middleware.MessageMiddleware’, ‘django.middleware.clickjacking.XFrameOptionsMiddleware’]

Template loader postmortem Django tried loading these templates, in this order:

Using engine django: * django.template.loaders.filesystem.Loader: /home/robline/skip/templates/base.html (Source does not exist) * django.template.loaders.filesystem.Loader: /home/robline/pep/templates/base.html (Source does not exist) * django.template.loaders.filesystem.Loader: /skip/templates/base.html (Source does not exist) * django.template.loaders.filesystem.Loader: /pep/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/contrib/admin/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/contrib/auth/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django_extensions/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/robline/robline.pythonanywhere.com/pep/templates/base.html (Source does not exist)

Template error: In template /home/robline/robline.pythonanywhere.com/pep/templates/pep_list.html, error at line 1 base.html 1 : <% extends «base.html» %>2 : <% block title %>PEP Badge List <% endblock %>3 : 4 : <% block extra-css %>5 : 6 : body < 7 : font-family: Sans-serif; 8 : font-size: 11px; 9 : >10 : 11 : .slice <

Traceback (most recent call last): File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/backends/django.py», line 61, in render return self.template.render(context) File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/base.py», line 170, in render return self._render(context) File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/base.py», line 162, in _render return self.nodelist.render(context) File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/base.py», line 938, in render bit = node.render_annotated(context) File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/base.py», line 905, in render_annotated return self.render(context) File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/loader_tags.py», line 127, in render compiled_parent = self.get_parent(context) File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/loader_tags.py», line 124, in get_parent return self.find_template(parent, context) File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/loader_tags.py», line 104, in find_template template_name, skip=history, File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/engine.py», line 129, in find_template raise TemplateDoesNotExist(name, tried=tried)

The above exception (base.html) was the direct cause of the following exception: File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/core/handlers/exception.py», line 47, in inner response = get_response(request) File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/core/handlers/base.py», line 202, in _get_response response = response.render() File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/response.py», line 105, in render self.content = self.rendered_content File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/response.py», line 83, in rendered_content return template.render(context, self._request) File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/backends/django.py», line 63, in render reraise(exc, self.backend) File «/home/robline/.virtualenvs/robline.pythonanywhere.com/lib/python3.6/site-packages/django/template/backends/django.py», line 84, in reraise raise new from exc

Exception Type: TemplateDoesNotExist at / Exception Value: base.html

the two lines you would have to add to «bruteforce» would be something like /home/robline/path/to/your/templates/dir/skip/templates

Источник

TemplateDoesNotExist at /app_name/

If you are facing above template error, there is a high possibility that at-least one of the below listed point applies to you.

1. Wrong template name:

Make sure when rendering the template, you are using right name of template. 

return render(request, 'app_name/tools.html', data)

Check if template name is actually tools or it is tool?

2. Wrong app name:

In the above render statement, confirm if the appname used is correct or not.

return render(request, 'app_name/tools.html', data)

3. Installed Apps:

Please confirm if your app is listed in installed apps in settings.py file.

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'your-app-here',
]

4. Template Directory Structure:

Make sure your templates are places inside a directory with same name as your app’s name which in itself is inside templates directory. Confused? 

So your templates directory structure should be as below.

app_name
|
|-templates
|    |-app_name
|    |    |-tools.html

5. Where is Django looking for templates:

Confirm if Django is looking for templates in app directories. For this you need to see templates setting in settings.py file. Check if APP_DIR is set to True. If this is set to False, Django won’t look for templates in app directories.

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',
],
},
},
]

6. Project level templates:

If you are using something like below in your project’s urls.py file

urlpatterns += [
path(r'robots.txt/', TemplateView.as_view(template_name="project_name/robots.txt", content_type='text/plain')),
]

It could be any file instead of robots.txt, then make sure there is templates directory in root directory of project. This template directory is outside of every app. Directory structure would be as below.

|-project_name
|    |-templates
|    |    |-project_name
|    |    |    |-your-template-here

These template files are project level template files.

Also add 'DIRS': [os.path.join(BASE_DIR, 'templates')],  in TEMPLATES tuple in settings.py file. BASE_DIR is defined in settings.py file at the top. If not define as below.

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

If you are still unable to resolve the error, feel free to comment or contact us or connect on facebook page.

Host your Django project for free.

Using IF ELSE condition in Django template

how to use IF ELSE in Django template, Syntax of IF, ELIF and ELSE in Django, Using filters within IF condition in Django template, Multiple elif (else if) confitions in Django template…

How to set a variable in Django template

Declaring a new variable in Django template, Set the value of a variable in Django template, using custom template tag in Django, Defining variables in Django template tag…

How to display flash messages in Django templates

flash messages in Django template, one-time notifications in Django template, messages framework Django, displaying success message in Django, error message display in Django…

5 lesser used Django template tags

rarely used Django template tags, lesser-known Django template tags, 5 awesome Django template tags, Fun with Django template tags,…

This error means Django was unable to find a particular template in your Django app , you might be asking yourself which template exactly is not being found ? Now for us to Know the exact template, we will have to go to our settings.py file and find this line


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

If you look at the documentation it describes the TEMPLATES variable as a list containing the settings for all template engines to be used with Django. Each item of the list is a dictionary containing the options for an individual engine.

By default Django is able to load templates from the templates subdirectory inside each installed application , the templates that cannot be found automatically are the ones which are not in our installed application , in short the templates that are in the same level as manage.py file are the ones that cannot be found automatically , read more on this here

So how do we find those templates outside of installed applications, we have to set the DIRS to point to the correct path where our template which are outside our installed appllication will be found . We will do this by setting the TEMPLATES variable like so


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',
            ],
        },
    },
]

As you can see, 'DIRS' above is set to point to the path where these templates will be found by using this line os.path.join(BASE_DIR, 'templates') . Now our templates which are outside the installed apps will be found easy by Django.

Resources

  • Django templates
  • source of photo used above

Понравилась статья? Поделить с друзьями:
  • Task host window при выключении windows 10 как исправить
  • Template kit install error
  • Temperature error пишет при запуске компьютера
  • Task handler raised error valueerror not enough values to unpack expected 3 got 0
  • Temperature error shutting down перевод