Django can't find template directory - python

I know there are many questions similar to this one, but none has solved my problem yet.
Python version: 3.4
Django version: 1.8
I get TemplateDoesNotExist at /lfstd/ when loading http://127.0.0.1:8000/lfstd/.
system.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
lfstd/views.py:
def index(request):
[...]
return render(request, 'lfstd/index.html', context_dict)
project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
url(r'^admin/', include(admin.site.urls)),
url(r'^lfstd/', include('lfstd.urls')),
lfstd urls.py:
from django.conf.urls import patterns, url
from lfstd import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'))
Running print on base_dir and template_path, I get:
Base dir: C:\Users\Phil\PycharmProjects\TownBuddies
Template path: C:\Users\Phil\PycharmProjects\TownBuddies\templates
Which is exactly where my project and template folder is located. However, django doesn't look in that folder for templates. It looks in the following folders:
C:\Python34\lib\site-packages\django\contrib\admin\templates\lfstd\index.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\auth\templates\lfstd\index.html (File does not exist)
In fact, if I move my template there, it does find it and it works.
Any help is very appreciated, I'm starting out with Django and completely stuck...
EDIT:
I changed TEMPLATE_DIRS to TEMPLATES but Django still isn't looking in the templates folder:

TEMPLATE_DIRS setting is deprecated in django 1.8. You should use the TEMPLATES instead:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_PATH],
'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',
],
},
},
]

I was doing some unit testing with pytest-django when suddenly I was getting repeated and completely unexpected ** TemplateDoesNotExist** errors.
I found this stackoverflow question while trying to figure out what was going on.
I finally solved the issue by deleting all the __pycache__ directories. I have since learned that when things suddenly go inexplicably wonky to clear out the __pycache__ before breaking things by trying to fix them!
I used this script to clear out all the __pycache__ directories recursively where a module with the following resides:
#!/usr/bin/env python
import os
import shutil
#!/usr/bin/env python
import os
import shutil
BASE_DIR = os.path.abspath(__file__)
print(BASE_DIR)
for root, dirs, files in os.walk(BASE_DIR):
for directory in dirs:
if directory == '__pycache__':
shutil.rmtree(os.path.join(root, directory))

Related

Django project template doesn't exist

Hi i'm just getting started with Django and i'm running a project, I have created an HTML file and this is the views.py
def index(request):
return render(request, "hello/index.html")
and this is the urls.py inside the maine file
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', include("hello.urls"))
]
and this is the urls.py inside the project file
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
and i got this error
view from my project
Make sure You have template folder same as where your manage.py
and also in settings.py
'DIRS': [os.path.join(BASE_DIR, 'templates')],
You have a typo. You have written templetes instead of templates
The problem is that you have simply misspelt the the template folder as templetes within your hello app. Rename it as templates and it will work
Add this to your main settings.py file.
and replace YOUR_APP_NAME with your django app name
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR, 'YOUR_APP_NAME/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',
],
},
},
]
Try creating the folder named templates inside the hello app. Then create a folder named by the app name 'hello'. That will enable django to read inside that folder and fetch for the template named index.html.
And the path will look like
projectDir/hello/templates/hello/index.html
Do so, hope it will help.

Trying to set up urls.py to direct to index.html

As the question implies, I am trying to set up my urls.py file to point towards my index.html file.
Here is the structure of my project:
-->mysiteX
---->.idea
---->mysite
------->migrations
__init__
admin.py
apps.py
models.py
test.py
views.py
---->mysiteX
-------->templates
index
---->css
---->fonts
---->js
---->vendors
__init__
settings
urls
wsgi
----->venv
db.sqlite3
manage
This is what my urls.py file looks like
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^index/', admin.site.urls),
]
my views.py file
from __future__ import unicode_literals
def index_file(request):
return render(request, "index.html")
settings.py:
import os, sys
abspath = lambda *p: os.path.abspath(os.path.join(*p))
PROJECT_ROOT = abspath(os.path.dirname(__file__))
sys.path.insert(0, PROJECT_ROOT)
TEMPLATE_DIRS = (
abspath(PROJECT_ROOT, 'templates'),
)
When I run manage.py I get this page
Update after making changes to my urls.py file to this extent:
from django.conf.urls import url
from django.contrib import admin
from gradientboost import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^/$',views.index_file,name='index')
]
This is what I am getting
Second Update
changed my settings.py file according to an answer given
import os, sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'mysiteX/templates')
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'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',
],
},
},
]
However still getting this error
You Need To Change Your Urls.py
Because You Are Changing Admin Url Admin Url Is For Admin Login And For Website Control!
and if you add index/ than you need to type in your brower like that domainname.com/index
So if you Want Your index.html show on website home page try my code:
Try This If You browsing this link 127.0.0.1:8000
from django.conf.urls import url
from django.contrib import admin
from mysite import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index_file, name='YOUR NAME')
]
And if you trying this link 127.0.0.1:8000/index Try This:
from django.conf.urls import url
from django.contrib import admin
from mysite import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/$', views.index_file, name='YOUR NAME')
]
Also Add This In Your Settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'mysiteX/templates')
And Also Add This In your Settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'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',
],
},
},
]
create a html template index.html and your url should be redirected the view.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', your_view, name = 'index'),
]
You don't reference templates from your urls.py. That is for matching routes up to view functions, and it is the view's job to tell Django to render a template, if appropriate. You already have a simple view that renders index.html, you just need to reference it in your urlconf.
If you want your index.html rendered at the root of your site, then you need to add this line to your urls.py (EDIT: fixed the route):
url(r'^$', index_file)
You will also need from mysite.views import index_file at the top of your urlconf.

TemplateDoesNotExist when using Django package

I followed this Django tutorial: https://docs.djangoproject.com/en/1.10/intro/reusable-apps/.
I have a project called oldcity and an app called oldantwerp. The app is located in a parent directory called django-oldantwerp and the app directory itself has a subdirectory templates. The index.html file that my project is looking for is situated like so:
django-oldantwerp>oldantwerp>templates>oldantwerp>index.html
I tried to use this app with my project by including it in settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'oldantwerp'
]
and in urls.py (in the projec), like so:
urlpatterns = [
url(r'^oldantwerp/', include('oldantwerp.urls')),
url(r'^admin/', admin.site.urls),
]
When I go to the admin page, everything works, but when I try to open the index page I get this error:
TemplateDoesNotExist at /oldantwerp/
It says it tried to locate the index.html file like so:
Template loader postmortem
Django tried loading these templates, in this order:
Using engine django:
* django.template.loaders.filesystem.Loader: /Users/Vincent/Apps/oldcity/templates/oldantwerp/index.html (Source does not exist)
* django.template.loaders.app_directories.Loader: /Users/Vincent/Apps/oldcity/venv/lib/python3.4/site-packages/django/contrib/admin/templates/oldantwerp/index.html (Source does not exist)
* django.template.loaders.app_directories.Loader: /Users/Vincent/Apps/oldcity/venv/lib/python3.4/site-packages/django/contrib/auth/templates/oldantwerp/index.html (Source does not exist)
And it also tried searching for another file: place_list.html, which is strange because I don't think I have such a file.
What could be wrong?
EDIT
This is the code of views.py in the oldantwerp folder:
class IndexView(generic.ListView):
template_name = 'oldantwerp/index.html'
context_object_name = 'places'
def get_queryset(self):
return Place.objects.order_by('id')[:]
EDIT
Maybe worth mentioning: it all did work when I just had a folder oldantwerp as a subdirectory in the oldicty project folder. This error only occurred after I started implementing it from an external package.
EDIT
These are my template settings in settings.py:
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',
],
},
},
]
One most likely problem could be you have got the template name wrong in your view. Ensure you use the template oldantwerp/index.html in the view, not just index.html.
If you look at your stacktrace you will see that you application tries to load the template from: * django.template.loaders.filesystem.Loader: /Users/Vincent/Apps/oldcity/templates/oldantwerp/index.html (Source does not exist).
If I read your first statement correctly your directory structure is:
django-oldantwerp>oldantwerp>templates>oldantwerp>index.html.
So you can either create a directory structure proper for django to identify your templates directory or you can update your templates constant from the settings file and point django to a physical location where it can find your templates.
You can try to set DIRS in settings.py like this: os.path.join(BASE_DIR, 'templates'), delete the oldantwerp folder from your templates folder and add index.html in templates.
After that, edit template_name = 'oldantwerp/index.html' to template_name = 'index.html'

Django 1.8 TEMPLATE_DIRS being ignored

This is driving me crazy. I've done something weird and it appears that my TEMPLATE_DIRS entries are being ignored. I have only one settings.py file, located in the project directory, and it contains:
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'web_app/views/'),
)
I'm putting project-level templates in the /templates folder, and then have folders for different view categories in my app folder (e.g. authentication views, account views, etc.).
For example, my main index page view is in web_app/views/main/views_main.py and looks like
from web_app.views.view_classes import AuthenticatedView, AppView
class Index(AppView):
template_name = "main/templates/index.html"
where an AppView is just an extension of TemplateView. Here's my problem: when I try to visit the page, I get a TemplateDoesNotExist exception and the part that's really confusing me is the Template-Loader Postmortem:
Template-loader postmortem
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
C:\Python34\lib\site-packages\django\contrib\admin\templates\main\templates\index.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\auth\templates\main\templates\index.html (File does not exist)
Why in the world are the 'templates' and 'web_app/views' directories not being searched? I've checked Settings via the debugger and a breakpoint in views_main.py and it looks like they're in there. Has anyone had a similar problem? Thanks.
What version of Django are you using? TEMPLATE_DIRSis deprecated since 1.8
Deprecated since version 1.8:
Set the DIRS option of a DjangoTemplates backend instead.
https://docs.djangoproject.com/en/1.8/ref/settings/#template-dirs
So try this instead:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
# insert your TEMPLATE_DIRS here
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customized them:
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Here's a link to an upgrade guide: https://docs.djangoproject.com/en/1.8/ref/templates/upgrading/

How to keep all my django applications in specific folder

I have a Django project, let's say "project1".
Typical folder structure for applications is:
/project1/
/app1/
/app2/
...
__init__.py
manage.py
settings.py
urls.py
What should I do if I want to hold all of my applications in some separate folder, 'apps' for example? So that structure should look like the following:
/project/
apps/
app1/
app2/
...
__init__.py
manage.py
settings.py
urls.py
You can add your apps folder to your python path by inserting the following in your settings.py:
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))
Then you can use all the apps in this folder just in the same way as they were in your project root!
You can do this very easily, but you need to change the settings.py to look like this:
INSTALLED_APPS = (
'apps.app1',
'apps.app2',
# ...
)
And your urls.py to look like this:
urlpatterns = patterns('',
(r'^app1/',include('apps.app1')),
(r'^app2/',include('apps.app2')),
)
.. and modify any imports to point to the app location
How about you utilize the BASE_DIR variable already present in the settings.py.
Just add the following:
import sys
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
Hope this helps.
As a slight variant to Berhard Vallant's or Anshuman's answers, here is an alternative snippet to place in settings.py
import os
import sys # Insert this line
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Insert the two lines below
APPS_DIR = os.path.join(BASE_DIR, '<your_project_dir_name>/apps/')
sys.path.insert(0, APPS_DIR)
Doing it in this way has the added benefit that your template directories are cleaner as they will look like below. Without the APPS_DIR variable, there will be a lot of repitition of <your_project_dir_name>/apps/ within the DIRS list of the TEMPLATES list.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(APPS_DIR, '<app_name>/templates/<app_name>'),
os.path.join(APPS_DIR, '<app_name>/templates/<app_name>'),
...
],
'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',
],
},
},
]
You can list the apps within the INSTALLED_APPS list as normal with either the short-form name given in apps.py or by using the long-form syntax of appname.apps.AppnameConfig replacing appname with your app's name.
It's easy and simple you need to add to settings.py
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))
and edit your app config for example
old app config:
class MyappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'myapp'
to new app config:
class MyappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
label='myapp'
name = 'apps.myapp'
than installed apps example:
INSTALLED_APPS = [
...
'apps.myapp.apps.MyappConfig'
...
]
I think it's very usefull and helpfull.Good luck :)
Just add __init__.py (4 underscores in total) in your apps folder. Now you can just do
urlpatterns = [
path('polls/',include('apps.polls.urls')),
path('admin/', admin.site.urls)
]
If you're using virtualenv/virtualenvwrapper (which is a bit dated but still valid), you can use the included add2virtualenv command to augment your python path:
mkdir apps
cd apps
pwd
[/path/to/apps/dir]
Copy that path to clipboard, then:
add2virtualenv /path/to/apps/dir
In my case, my project folder structure is the following:
/project/
/apps/
/app1/
/app2/
/src/
/settings.py
...
So I've solved it with these two lines on my settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(BASE_DIR, '../apps'))
No need to alter urls.py.
By using manage.py
# Fisrt create apps folder and appname subfolder
mkdir -p ./apps/<appname>
# Then create new app
python manage.py <appname> ./apps/<appname>

Categories