Template doesnot exist error in Django - python

Am developing an angular frontend and Django backend app.I don't know where i am going wrong but Django cant seem to locate the template and displays a template doesn't exist message.The project directory looks like this.The backend server is in the "django project" folder
base.py(settings)
import environ
project_root = environ.Path(__file__) - 3
env = environ.Env(DEBUG=(bool, False),)
CURRENT_ENV = 'dev' # 'dev' is the default environment
# read the .env file associated with the settings that're loaded
env.read_env('./mysite/{}.env'.format(CURRENT_ENV))
#Database
DATABASES = {
'default': env.db()
}
SECRET_KEY = env('SECRET_KEY')
DEBUG = env('DEBUG')
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Django Packages
'rest_framework',
'mysite.applications.games',
]
ROOT_URLCONF = 'mysite.urls'
STATIC_URL = '/static/'
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
STATICFILES_DIRS = [
env('FRONTEND_ROOT')
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [env('FRONTEND_ROOT')],
'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',
],
},
},
]
Environment variables file(dev.env)
DATABASE_URL=sqlite:///mysite.db
DEBUG=True
FRONTEND_ROOT= ('C:/downloads/mysite/frontend/')
SECRET_KEY= '##########################'
urls.py
from django.contrib import admin
from django.conf.urls import include, url
from mysite.applications.api.v1.routes import api_router
from django.views.generic import TemplateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
# Web App Entry
url(r'^$', TemplateView.as_view(template_name="/app/index.html"), name='index'),
]

I changed template DIRS setting to point to 'C:/downloads/mysite/frontend/' and also the template name to point to "/app/index.html".app is a folder inside frontend.

Related

Django Login Required Middleware does not redirect

I'm super new to Django and I have created a middleware that should direct my users to the index page with login view when trying to access the pages that are supposed to work only for logged users. Even though I don't get any error in my terminal, it does not work. When I type http://127.0.0.1:8000/profile/ in my browser, I'm still able to see it. Instead of that, I would like to direct my users to the login page.
movie_project/middleware.py
from django.http import HttpResponseRedirect
from django.conf import settings
from re import compile
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_request(self, request):
assert hasattr(request, 'user')
if not request.user.is_authenticated():
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
return HttpResponseRedirect(settings.LOGIN_URL)
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = ''
DEBUG = True
ALLOWED_HOSTS = []
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
# Application definition
INSTALLED_APPS = [
'movies_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'multiselectfield'
]
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',
'movie_project.middleware.LoginRequiredMiddleware',
]
LOGIN_URL = 'movies_app.views.index'
LOGIN_URL = '/index/'
MIDDLEWARE_CLASSES = (
'python.path.to.LoginRequiredMiddleware',
)
ROOT_URLCONF = 'movie_project.urls'
AUTH_USER_MODEL = 'movies_app.User'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
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',
'django.template.context_processors.media',
],
},
},
]
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, 'templates'),
)
WSGI_APPLICATION = 'movie_project.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import editprofile
from . import views
app_name = 'movies_app'
urlpatterns = [
path('', views.login, name='login'),
path('browse/', views.index, name='index'),
path('register/', views.register, name='register'),
path('movies/', views.allMovies, name='allMovies'),
path('movies/<int:pk>/', views.movie, name='movie'),
path('movies/<int:pk>/rate', views.addRating, name='rate'),
path('my-list/', views.myMovies, name='my-list'),
path('my-list/<int:pk>/delete', views.deleteFavoriteMovie, name='favorite-movie-delete'),
path('profile/', views.profile, name='register'),
path('editprofile/', views.editprofile, name='editprofile'),
path('logout/', views.logout, name='logout'),
path('movie-video', views.movieVideo, name='movie-video')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Anyone knows where can be a problem? Thank you so much for any help!
Your login required middleware does not appear to be doing anything outside of the normal. Is there a reason you have not simply used the login_required decorator on some of your views?
This decorator can be added to any (class based or function based) view where authentication is required. For example
from django.contrib.auth.decorators import login_required
#login_required
def movies_list(request):
...
This will then automatically render the view for all users who are logged in and otherwise redirect the user to the LOGIN_URL if not authenticated.
Whilst you can run your own middleware for such auth, I would strongly use the battle-tested options within the Django framework.
In the case of your comment above:
When I type http://127.0.0.1:8000/profile/ in my browser, I'm still able to see it. Instead of that, I would like to direct my users to the login page.
On your profile view function or class base method simply add #login_required with the appropriate import statement (from django.contrib.auth.decorators import login_required).
It's somewhat confusing to have two variables named the same thing in settings.py?
LOGIN_URL = 'movies_app.views.index'
LOGIN_URL = '/index/'
They're just above MIDDLEWARE_CLASSES. Here' a reference to the HTTPResponseRedirect. https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.HttpResponseRedirect In other words, delete the one that says movies_app.views.index

Ckeditor/ django 2.0 admin body input disappeared

I recently installed Ckeditor on django 2.0, turns out some of the css and js files are not loading properly, I manage to get Ck read the files but now my admin body input was disappeared. missing-admin-body
As I am pretty new to django, I was wondering if I were doing anything wrong in the setting. (try to make a blog, url + generic view set up)
setting.py
>
INSTALLED_APPS = [
'personal',
'blog',
'contact',
'widget_tweaks',
'ckeditor',
'ckeditor_uploader',
'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 = 'mysite.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.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/2.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/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'EST'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_DIR = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URLS = '/media/'
# sendmail setting
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DEFAULT_FROM_EMAIL = 'kai.peng#uconn.edu'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
EMAIL_PORT = 1025
#CKeditor meida.root, and other setting
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_BASEPATH = "{% static 'ckeditor/ckeditor/' %}"
CKEDITOR_FILENAME_GENERATOR = 'utils.get_filename'
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_JQUERY_URL = os.path.join(STATIC_URL,'js/jquery.min.js')
CKEDITOR_CONFIGS = {
'awesome_ckeditor': {
'toolbar': 'Basic',
},
}
here is my blog/url.py
>
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
from django.urls import re_path, path
urlpatterns = [
path('', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:25],
template_name="blog/blog.html")),
path('blog/<pk>/', DetailView.as_view(
model = Post,
template_name="blog/post.html")),]
And here is my blog/views.py
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
from django.urls import path, re_path
from django.shortcuts import render
urlpatterns = [
path(r'', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:25],
emplate_name="blog/blog.html")),
path('blog/<int:id>/', DetailView.as_view(
model = Post,
template_name="blog/post.html")),
]
And this is my model.py
>
from django.db import models
from ckeditor.fields import RichTextField
class Post(models.Model):
title = models.CharField(max_length = 140,null = True)
body = RichTextField(config_name='awesome_ckeditor')
date = models.DateTimeField(null = True)
name = models.CharField(max_length=128,null = True)
def __str__(self):
return self.title
this is the console view when I tried to refresh admin edit page
console view
I am using a python 3.6X and Django 2.0, on a Windows platform.
here is the website response with the 'empty body' site response
I suspect theres problem on the db integration or model registration, not sure....
admin.py
from django.contrib import admin
from blog.models import Post
admin.site.register(Post)
# Register your models here.
In my case it was about installing required plugins, I added following line to CKEDITOR_CONFIGS but I forgot to download these plugins and put them inside static folder
'extraPlugins': ','.join(['codesnippet', 'prism', 'widget', 'lineutils', 'clipboard']),
I also specified plugin directories like this:
CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/"
BTW make sure plugin folder's name inside this directory is the same with plugin's name, as you download plugins as zip and then extract it, its name can be a bit different...
This was all I have done to fix my issue.

Django is not rendering second applications HTML

I've added a second application using:
python manage.py startapp about
in my project. However now it is rendering my first applications only view, no matter what URL I put on.
Ex. http://127.0.0.1:8000/aldsjfal/asdfadsfa/adsfasdf/adfadsf/
Here is my settings.py:
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
################################################################################
# Dependencies #
################################################################################
import os.path #
# #
# Note that we use os.path to construct the absolute path. This ensures Django#
# can locate the files unambiguously for STATICFILES_DIRS. - LT 16JAN2016 #
# #
# #
# #
################################################################################
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.realpath(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*ih=!lu+z1=5sk8&ool2hmryc07rbuhjwy*3745=i6#$w)joo7'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
Temp_Path = os.path.realpath('.')
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = PROJECT_PATH + '/media/'
# Application definition
INSTALLED_APPS = [
'about.apps.AboutConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home.apps.HomeConfig',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'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'
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',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/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/1.9/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/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
----------------------------------EDIT 1----------------------------------
Here is my urls.py from the root project:
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Import the include() function: from django.conf.urls import url, include
3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^about/', include('about.urls'), name ='about'),
url(r'^', include('home.urls'), name ='index'),
url(r'^admin/', admin.site.urls),
]
Here is my first application urls.py:
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
app_name = 'home'
from . import views
urlpatterns = [
url(r'^', views.index, name ='index'),
]
Here is my second applications urls.py:
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
app_name = 'about'
from . import views
urlpatterns = [
url(r'^/about/$', views.about, name ='about'),
]
The order of url patterns matter. It will return any first matching pattern at the top of the list, even though there could be more specific pattern at the bottom of the list.
also a pattern like: r’^‘ will match anything. including: http://127.0.0.1:8000/abc/def/ghi/. However, normally such pattern will include another nested urlpattern, where they usually will be closed with some kind of r'^$', which match nothing more.
You need to add "about" app in your settings.py file under the INSTALLED_APPS. Like this:
INSTALLED_APPS = [
'about.apps.AboutConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home.apps.HomeConfig',
'about',
]
Go to url.py and configure the URL like:
urlpatterns = patterns(‘’,
url(r’^$’, HomePageView.as_view(), name=‘home’),
url(r’^about/‘, include(‘blog.urls’)),
...
)
Go to settings.py and add more eventual modules:
INSTALLED_APPS = [
'about.apps.AboutConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home.apps.HomeConfig',
'new_module',
]

django 1.9 and registration/login.html

I'm working on a django 1.9 project.
With Django 1.7.7, login functionnalities was working, but now all the time I have : registration/login.html : Template Does Not Exist
The templates login.html, logout.html are present in 'webgui/template/registration/' and I didn't modified them.
Here some of my settings.py :
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webgui',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'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 = 'project.urls'
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',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'NCIS.db'),
}
}
STATIC_URL = '/static/'
LOGIN_REDIRECT_URL = '/login/'
LOGOUT_URL = '/logout/'
DIRS = (
join(BASE_DIR, 'webgui/template/registration'),
join(BASE_DIR, 'webgui/template/')
)
And my urls.py :
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth.views import login, logout
import webgui.views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', login, name='login.html'),
url(r'^login/$', login, name='login.html'),
url(r'^logout/$', logout, name='logout.html'),
url(r'^homepage/$', webgui.views.homepage),
url(r'^addproject/$', webgui.views.addproject)
]
What's wrong? I checked the Django docs, but that's the default behaviour.
This question appears first in search engine with searching for
registration/login.html : Template Does Not Exist
So for those coming through search engine, please note that this template doesn't come by default with Django. If you haven't created it, that's why you are getting this error
Here is how you can create a simple one
https://simpleisbetterthancomplex.com/tutorial/2016/06/27/how-to-use-djangos-built-in-login-system.html
Try to put your template dirs paths in DIRS list inside TEMPLATES setting. (Anyway, your template folder name should be templates not template.)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [join(BASE_DIR, 'webgui/template/registration'),join(BASE_DIR, 'webgui/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',
],
},
},
]
After upgrading my django to 1.9.1, same thing happened to me. Apparently, there are updates on templates directory.
Here is how I fixed it.
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',
],
},
},
]
Of course you should have BASE_DIR defined
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
After that,I've deleted the templates folder and created a templates folder for each app. So, inside the each app, just create templates and put the html files inside.
Also in views, connect it to the html file like this.
def index(request):
context_dict = {}
return render(request, 'index.html', context_dict)
This worked for me.
You have set 'APP_DIRS': True,, so Django will search for templates directories inside each app in INSTALLED_APPS, including your webgui app.
The problem is that you have named your directory webgui/template/ instead of webgui/templates/, so the app loader won't find it.
The easiest fix is to rename your directory. If you don't want to do this, you'll have to add the webgui/template directory to your DIRS option.

Why does Django raise "KeyError"?

I am currently trying to implement pagination to my Django web app. However, when I try to use template tags from the library, Django raises a key error. To be specific:
KeyError
KeyError: 'request'
Here is my settings.py:
from django.core.urlresolvers import reverse_lazy
from os.path import dirname, join, exists
import os
# Build paths inside the project like this: join(BASE_DIR, "directory")
BASE_DIR = dirname(dirname(dirname(__file__)))
STATICFILES_DIRS = [join(BASE_DIR, 'static')]
MEDIA_ROOT = join(BASE_DIR, 'media')
MEDIA_URL = "/media/"
# Use Django templates using the new Django 1.8 TEMPLATES settings
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
join(BASE_DIR, 'templates'),
# insert more 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',
],
},
},
]
# Use 12factor inspired environment variables or from a file
import environ
env = environ.Env()
# Ideally move env file should be outside the git repo
# i.e. BASE_DIR.parent.parent
env_file = join(dirname(__file__), 'local.env')
if exists(env_file):
environ.Env.read_env(str(env_file))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.auth',
'django_admin_bootstrapped',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'authtools',
'crispy_forms',
'easy_thumbnails',
'geoposition',
'bootstrap_pagination',
'profiles',
'accounts',
'clients',
)
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 = 'saas.urls'
WSGI_APPLICATION = 'saas.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/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/dev/howto/static-files/
STATIC_URL = '/static/'
ALLOWED_HOSTS = []
# Crispy Form Theme - Bootstrap 3
CRISPY_TEMPLATE_PACK = 'bootstrap3'
# For Bootstrap 3, change error alert to 'danger'
from django.contrib import messages
MESSAGE_TAGS = {
messages.ERROR: 'danger'
}
# Authentication Settings
AUTH_USER_MODEL = 'authtools.User'
LOGIN_REDIRECT_URL = reverse_lazy("profiles:show_self")
LOGIN_URL = reverse_lazy("accounts:login")
THUMBNAIL_EXTENSION = 'png' # Or any extn for your thumbnails
The template-tag I am trying to run is:
{% block pagination %}
{% bootstrap_paginate page_obj range=10 show_prev_next="false" show_first_last="true" %}
{% endblock %}
What to do?
The bootstrap_paginate template tag expects your template context to contain the request variable. Make it available by changing your context_processors to:
'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',
'django.contrib.auth.context_processors.request', # <-- Here we add the request
],
if you have imported
import django_heroku
Then put this:
django_heroku.settings(local())
in the end of your settings.py file

Categories