TemplateDoesNotExist at/ on Django - python

I have the project like this:
├── manage.py
├── myProjet
│ ├── __init__.py
│ ├── settings.py
│ ├── templates
│ ├── urls.py
│ ├── wsgi.py
│ └── wsgi.pyc
├── app1
├── templates
When I run the project, I am always getting this error: TemplateDoesNotExist at/
I have tried everything, but I can't fix it. My settings.py file is this:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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',
],
},
},
]
I have tried many ways, but I am always getting errors.
The error is raised on the signup function. The function is this:
def SignupPage(request):
if request.method=='POST':
uname=request.POST.get('username')
email=request.POST.get('email')
pass1=request.POST.get('password1')
pass2=request.POST.get('password2')
if pass1!=pass2:
return HttpResponse("Your password and confrom password are not Same!!")
else:
my_user=User.objects.create_user(uname,email,pass1)
my_user.save()
return redirect('login')
return render (request,'signup.html')
UPDATE ERROR
TemplateDoesNotExist at /
signup.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 4.1.6
Exception Type: TemplateDoesNotExist
Exception Value:
signup.html
Exception Location: /home/myPC/myProject/my_env/lib/python3.8/site-packages/django/template/loader.py, line 19, in get_template
Raised during: app1.views.SignupPage
Python Executable: /home//myProject/my_env/bin/python
Python Version: 3.8.10
Python Path:
['/home/myPC/myProject/pmTools_V1',
'/usr/lib/python38.zip',
'/usr/lib/python3.8',
'/usr/lib/python3.8/lib-dynload',
'/home/myPC/myProject/my_env/lib/python3.8/site-packages']

Since django is using pathlib I'd go with:
"DIRS": [
BASE_DIR / "templates"
],
in your settings.py templates section.

Try to replace:
'DIRS': ['templates'],
By:
'DIRS': [os.path.join(BASE_DIR, 'templates')]
in TEMPLATES section.
Update
Try:
from django.http import HttpResponse
from django.template import loader
def SignupPage(request):
template = loader.get_template('signup.html')
# Your code here
return HttpResponse(template.render(context, request))

Related

Django tamplate can not loaded

I called a template in the django render function, but django cannot find it
here is the django view code:
from django.shortcuts import render
# Create your views here.
def home_page(request):
return render(request, "index.html")
And after this I tried to check my settings.py and urls.py, but found nothing, and the file is also in the tamplate subfolder of the app
here is the directory structure:
│ .gitignore
│ db.sqlite3
│ funcational_test.py
│ manage.py
│
├─Terminal_equipment_management
│ │ asgi.py
│ │ settings.py
│ │ urls.py
│ │ view.py
│ │ wsgi.py
│ │ __init__.py
│ │
│ └─__pycache__
│
└─webui
│ admin.py
│ apps.py
│ models.py
│ tests.py
│ views.py
│ __init__.py
│
├─migrations
│
├─templates
index.html
the settings.py is:
INSTALLED_APPS = [
"api",
"webui",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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',
],
},
},
]
urls.py is:
from django.contrib import admin
from django.urls import path, include
from webui import views
urlpatterns = [
path("", views.home_page, name="home_page"),
]
But when I visit localhost:8000/, Django will report TemplateDoesNotExist at /
here is some Error Message:
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\ProgramData\Miniconda3\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\ProgramData\Miniconda3\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist)
When I copied the files to the above two folders, the template took effect.
I can't be sure what happened
By Google Translate
Add Template DIRS:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / "template"],
'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 think you forgot to put s for template folder names
└─webui
│
├─tamplates
index.html
First, tamplates should be templates. Second, django looks inside a folder under templates for the app name. It seems redundant, and I agree, but that caused me issues when I was first using django.
└─webui
│
└─templates
│
└─webui
│
└─index.html

AttributeError: module 'app.management.commands.api' has no attribute 'Command' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a file to fetch info from a API (UK Company House). To test I have
import requests
r = requests.get('https://api.companieshouse.gov.uk/company/00002065', auth=('xxxxx', ''))
print(r.text)
It works and produces the data, but then after the data I get the following error message
AttributeError: module 'app.management.commands.api' has no attribute
'Command'
Why is this and how do I resolve?
Edit - Additionally, if I run "py ch_api.py" in the same folder the file is located it works with no error; only when I run "py manage.py ch_scrape" I get the error (I need to run it through the second method)
Edit 2 - Some further info
Files
project
├── __init__.py
├── manage.py
├── fetches
├── management
├── __init__.py
├── commands
├── ch_api.py
├── __init__.py
└── project
├── __init__.py
├── asgi.py
├── settings.py
├── urls.py
├── views.py
├── wsgi.py
My manage.py file
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
My settings.py file
"""
Django settings for project project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*******'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles'
]
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',
]
ROOT_URLCONF = 'project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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',
],
},
},
]
WSGI_APPLICATION = 'project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'assets'),
)
Ok - got it. Coming from Rails, I'm not sure what or why Command(BaseCommand) is required, but learning as I go. If anyone wants to pop a small nudge to what this is all about, it would be appreciated.
from django.core.management.base import BaseCommand, CommandError
import requests
class Command(BaseCommand):
def handle(self, *args, **options):
r = requests.get('https://api.companieshouse.gov.uk/company/00002065', auth=('DKvKM78qjU0Er_PGYnAdfSpgNquuz9LA_GYp1KNY', ''))
print(r.text)

How to load external html into html inside Django template

I am trying to incorporate a django application into a web site where static html accounts for the majority.
The directory structure is as follows.
root/
 ├ var/
 │  └ www/
 │   ├ html/
 │    ├ static
 │    │ ├style.css
 │    │ ├base.js
 │    │
 │    ├ web/
 │      ├head.html
 │      ├footer.html
 │      ├base.html
 │
 └ opt/
   └ django/
     ├ project/
     │
     ├ apps/
     ├ ├ views.py
       ├ template/
        ├ index.html
I want to make /opt/django/template/index.html read html in /var/www/html/web/.
I do not know how to include.
{% include "/var/www/html/web/head.html" %}was useless.
I do not want to change the directory structure.
Considering this as your directory structure:
root/
 ├ var/
 │  └ www/
 │   ├ html/
 │    ├ static
 │    │ ├style.css
 │    │ ├base.js
 │    │
 │    ├ web/
 │      ├head.html
 │      ├footer.html
 │      ├base.html
 │
 └ opt/
   └ django/
     ├ project/
     │
     ├ apps/
     ├ ├ views.py
       ├ template/
        ├ index.html
To use /var/www/html/web/head.html in your index.html.
Go to your settings.py and add this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'apps/template'),'/var/www/html/web/']
,
'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',
],
},
},
]
Now go to your index.html.
{% include "head.html" %}
I hope this will help.
Add /var/www/html/web/ to the DIRS option in the template configuration dictionary in your project settings.
https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-TEMPLATES-DIRS
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/var/www/html/web/'], # won't work on Windows
'APP_DIRS': True,
'OPTIONS': {
# ... some options here ...
},
},
]
Then:
{% include "head.html" %}
Your templates can go anywhere you want. Your template directories are by using the DIRS option in the TEMPLATES setting in your settings file.
For each app in INSTALLED_APPS, the loader looks for a templates subdirectory. If the directory exists, Django looks for templates in there.
note
Paths should use Unix-style forward slashes, even on Windows.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'/var/www/html/web/',
],
},
]

Django 1.10 404.html template not found

As far as I have seen in the Django documentation, to show a custom 404 page all you have to do is put a 404.html in the root templates directory.
So my project structure is:
django_project
|_ config
| |_ settings.py
| |_ urls.py
|
|_ templates
|_ base.html
|_ index.html
|_ 404.html
In settings.py I have the following settings for the templates:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["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',
'contact.views.contact_info',
],
},
},
]
for the 'DIRS' parameter I also used os.path.join(BASE_DIR, "templates"). This had the exact same outcome.
I also used
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, "templates"),
)
This lead to a deprecation warning.
In urls.py I also did not really do anything special:
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="index.html"), name="index"),
url(r'^admin/', admin.site.urls),
]
Template inheritance is working perfectly in other apps, so the templates directory is found.
In settings: DEBUG=False
When I enter a wrong url I get the Django default 'NOT FOUND' page.
What am I missing here?
you need override 'handler404' variable, add this to urls.py
from django.conf.urls import handler404
handler404 = 'your_app.views.404'
https://docs.djangoproject.com/en/1.10/topics/http/views/#customizing-error-views
I guess you have to specify route for your 404.html template, or use from django shortcuts 'get_object_or_404' to handle error 404.

Django Template Doesn't Exist doesn't check top-level .html?

I'm trying to point Django to a top-level about.html of mysite, however Django doesn't seem to check for the file at mysite/about.html , mysite/templates/about.html or mysite/templates/mysite/about.html (I've put about.html in all 3 of these places)
I'm getting TemplateDoesNotExist error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
c:\users\jerry hou\documents\projects\django-trunk\django\contrib\admin\templates\about.html (File does not exist)
c:\users\jerry hou\documents\projects\django-trunk\django\contrib\auth\templates\about.html (File does not exist)
c:\Users\Jerry Hou\Documents\Projects\mysite\polls\templates\about.html (File does not exist)
#Why doesn't check inside mysite\mysite\ but only in mysite\polls\?
Here's the file directory structure of Django mysite:
mysite/
manage.py
polls/
__init__.py
admin.py
migrations/
__init__.py
models.py
tests.py
views.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
mysite/mysite/urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from mysite import views
urlpatterns = [
# Examples:
url(r'^$', 'mysite.views.index', name='mysite_home'),
url(r'^about/$', views.AboutView.as_view(), name='mysite_about'),
url(r'^polls/', include('polls.urls', namespace = "polls")),
url(r'^admin/', include(admin.site.urls)),
]
The following worked for me:
mysite/
├── db.sqlite3
├── manage.py
├── mysite
│   ├── __init__.py
│   ├── __pycache__
│   │  ...<omitted>...
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
└── templates
└── mysite
└── index.html
mysite/mysite/settings.py:
"""
Django settings for mysite project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
####CHECK THIS OUT####
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-d^1m(a3a*^$*m#v20_r$66bqy29*q6m#r)!-s)tv7y^#jy%qa'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
mysite/mysite/views.py:
from django.http import HttpResponse
from django.template import Context, loader
def index(request):
#return HttpResponse('hello world')
templ = loader.get_template('mysite/index.html') #Use the path within the templates dir
context = Context(
{'planet': 'world'}
)
return HttpResponse(
templ.render(context)
)
mysite/templates/mysite/index.html:
<div>Hello</div>
<div>{{planet}}</div>
mysite/mysite/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from mysite import views #NOTE THIS*********
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', views.index),
url(r'^admin/', include(admin.site.urls)),
)
Why doesn't check inside mysite\mysite\?
You can make django do that by changing settings.py to:
...
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'mysite/templates'),
)
...
...and adding a templates directory here:
mysite
├── db.sqlite3
├── manage.py
├── mysite
│   ├── __init__.py
│   ├── __pycache__
│   │   ...<omitted>...
│   ├── settings.py
│   ├── templates
│   │   └── index.html
Them mysite/mysite/views.py would look like this:
from django.http import HttpResponse
from django.template import Context, loader
def index(request):
#return HttpResponse('hello world')
templ = loader.get_template('index.html') #Use the path within the templates dir
context = Context(
{'planet': 'world'}
)
return HttpResponse(
templ.render(context)
)
You should create templates directory in the project root and add the following setting to mysite/settings.py:
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
TEMPLATE_DIRS documentation is here.

Categories

Resources