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.
Related
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))
Let's say I've got the classic "School" app within my Django project. My school/models.py contains models for both student and course. All my project files live within a directory I named config.
How do I write an include statement(s) within config/urls.py that references two separate endpoints within school/urls.py? And then what do I put in schools/urls.py?
For example, if I were trying to define an endpoint just for students, in config/urls.py I would do something like this:
from django.urls import path, include
urlpatterns = [
...
path("students/", include("school.urls"), name="students"),
...
]
And then in school/urls.py I would do something like this:
from django.urls import path
from peakbagger.views import StudentCreateView, StudentDetailView, StudentListView, StudentUpdateView, StudentDeleteView
urlpatterns = [
# ...
path("", StudentListView.as_view(), name="student-list"),
path("add/", StudentCreateView.as_view(), name="student-add"),
path("<int:pk>/", StudentDetailView.as_view(), name="student-detail"),
path("<int:pk>/update/", StudentUpdateView.as_view(), name="student-update"),
path("<int:pk>/delete/", StudentDeleteView.as_view(), name="student-delete"),
]
But how do I do I add another urlpattern to config/urls.py along the lines of something like this? The include statement needs some additional info/parameters, no?
from django.urls import path, include
urlpatterns = [
...
path("students/", include("school.urls"), name="students"),
path("courses/", include("school.urls"), name="courses"),
...
]
And then what happens inside of school/urls.py?
I'm open to suggestions, and definitely am a neophyte when it comes to the Django philosophy. Do I need an additional urls.py somewhere? I'd prefer not to put everything in config/urls.py and I'd prefer not to build a separate app for both students and courses.
I would rather create two (or more) urls.py files and then point them separately.
# directory structure
school/
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
├── urls
│ ├── course.py
│ ├── __init__.py
│ └── student.py
└── views.py
# school/urls/course.py
from django.urls import path
from school.views import CourseListView
urlpatterns = [
path("", CourseListView.as_view(), name="course_list"),
# other URLs
]
# school/urls/student.py
from django.urls import path
from school.views import StudentListView
urlpatterns = [
path("", StudentListView.as_view(), name="student_list"),
# other URLs
]
# config/urls.py
from django.urls import include, path
urlpatterns = [
path("student/", include("school.urls.student")),
path("course/", include("school.urls.course")),
# other URLs
]
The best solution for you is to make separate urls directory inside your app
For example if you have school as app then
app
├── School
│ ├── views.py
│ └── models.py
| └── urls
| └── __init__.py
| └── urls.py
| └── school_urls.py
| └── course_urls.py
Now in your main project urls you can set this way
urlpatterns = [
...
path("", include("school.urls"), name="students"),
...
]
and in urls.py of your school urls folder you can do this way
urlpatterns = [
...
path("students/", include("school.urls.school_urls"), name="students"),
path("course/", include("school.urls.course_urls"), name="course"),
...
]
and you can do add course view in course url folder and another student view in student urls file
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)
I am trying to connect zinnia to django-cms 3.0
I have launched zinnia and it works just fine. Now I am trying to start changing styles. More specifically templates/zinnia/skeleton.html override.
Once I add template to override original template - url reverse starts on failing.
NoReverseMatch at /en-us/blog/
Reverse for 'entry_archive_index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
All of the urls use namespace as in {% url 'zinnia:entry_archive_index' %} and yet reverse in shell also just fails.
What else could be done to debug it? Maybe it's because of localization?
I have urls config:
from django.conf.urls import patterns, url, include
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = i18n_patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/', include('zinnia.urls', namespace='zinnia')),
url(r'^comments/', include('django.contrib.comments.urls')),
url(r'^tinymce/', include('tinymce.urls')),
url(r'^', include('cms.urls')),
)
if settings.DEBUG:
urlpatterns = patterns(
'',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns
Settings:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.comments',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.contenttypes',
'my_main_django_cms_app',
'cms',
'mptt',
'menus',
'south',
'sekizai',
'djangocms_text_ckeditor',
'djangocms_picture',
'djangocms_inherit',
'djangocms_googlemap',
'cmsplugin_contact',
'tinymce',
'tagging',
'zinnia_threaded_comments',
'zinnia',
'cmsplugin_zinnia',
)
And my_main_django_cms_app structure is
.
├── cms_plugins.py
├── forms.py
├── __init__.py
├── manage.py
├── models.py
├── settings.py
├── static
├── templates
│ ├── base.html
│ ├── home.html
│ └── zinnia
│ └── skeleton.html
├── urls.py
├── wsgi.py
And my versions:
Django==1.6.5
Pillow==2.4.0
South==0.8.4
argparse==1.2.1
beautifulsoup4==4.3.2
cmsplugin-contact==1.0.0
cmsplugin-zinnia==0.6
django-app-namespace-template-loader==0.1
django-blog-zinnia==0.14.1
django-classy-tags==0.5.1
django-cms==3.0
django-mptt==0.6.0
django-reversion==1.8.1
django-sekizai==0.7
django-tagging==0.3.2
django-tinymce==1.5.2
django-xmlrpc==0.1.5
djangocms-admin-style==0.2.2
djangocms-googlemap==0.0.5
djangocms-inherit==0.0.1
djangocms-picture==0.0.2
djangocms-text-ckeditor==2.1.6
gevent==1.0.1
greenlet==0.4.2
gunicorn==19.0.0
my_main_django_cms_app==0.1
html5lib==1.0b3
ipdb==0.8
ipython==2.1.0
psycopg2==2.5
pyparsing==2.0.2
pytz==2014.4
six==1.7.2
wsgiref==0.1.2
zinnia-threaded-comments==0.2
I have been trying to integrate zinnia into django cms for a few days, and here's my experience, which gets me to the point where I can use my own django cms template for zinnia, but I'm still not getting the menus provided with cmsplugin_zinnia to work.
Compared to your setup, I've made the following changes:
Deleted zinnia namespace, so url(r'^blog/', include('zinnia.urls', namespace='zinnia')) becomes url(r'^blog/', include('zinnia.urls')).
Added app_name = 'zinnia' to cmsplugin_zinnia.cmsapp.ZinniaApphook
Moved cms after zinnia and before cmsplugin_zinnia from settings.py in demo_cmsplugin_zinnia
With this, I can select Zinnia Weblog as Application under Advanced Settings for a new Django CMS page, and give it a unique Application Instance Name as suggested in the Django CMS docs. The name of the page or its url/slug field don't matter.
From here I can come up with my own skeleton.html that makes no reference to zinnia whatsoever, and have zinnia.base.html extend my new skeleton template.
However, at this point the cmsplugin_zinnia docs suggest:
'Once the apphook is registered, you can remove the inclusion of zinnia.urls in urls.py and then restart the server to see it in full effect.',
but instead I get a NoReverseMatch at /name_of_my_blog_app/ exception, which only disappears if I include the zinnia.urls as above without namespace.
As a few weeks have passed since your original post, you may have resolved this by now. If not, I hope this points you into the right direction. In case you ran into the same issues (EntryMenu not loaded) at some point and were able to resolve, please let me know.
By using dev version for django-blog-zinnia, I see 'EntryMenu not loaded' no more. All menus related errors are gone now. As my understanding goes, this is due to inherent namespace issue in zinnia. Fantomas42 looks covering it in development version.
It has been tracked on https://github.com/django-blog-zinnia/cmsplugin-zinnia/issues/29
Let's assume I have the following project:
myproject/
myproject/
__init__.py
settings.py
urls.py
wsgi.py
templates/
base.html
app1/
__init__.py
admin.py
models.py
urls.py
views.py
templates/
base.html
index.html
I want to have a base template, which all other apps will use, in myproject/template/base.html.
Then, I want to have the app templates in app/templates.
One option would be writting in myproject/settings.py:
TEMPLATE_DIRS = (
"/dir/to/myproject/myproject/templates",
"/dir/to/myproject/app1/templates",
)
But, is this the best way to do it?
Django supports this automatically, via the app_directories loader that is installed by default. See the documentation.
Maybe you can do the following:
#settings.py
import os
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH, 'templates'),
os.path.join(PROJECT_PATH, 'app1/templates'),
)
This will save you from editing each and every absolute path in setting file in case you happen to move your project.