TypeError: 'module' object is not callable Django 3 render function - python-3.x

I am just making a simple hello world page in my Django 3 Application I am getting error
TypeError: 'module' object is not callable
Here is the error
TypeError at /
'module' object is not callable
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.0.11
Exception Type: TypeError
Exception Value:
'module' object is not callable
Exception Location: C:\Users\admin\AppData\Roaming\Python\Python37\site- packages\django\template\context.py in bind_template, line 246
Python Executable: C:\Program Files (x86)\Microsoft Visual
Studio\Shared\Python37_64\python.exe
Python Version: 3.7.8
Python Path:
['C:\\Users\\admin\\Repositories\\django-docker\\django-portal-base\\app',
'C:\\Program Files (x86)\\Microsoft Visual '
'Studio\\Shared\\Python37_64\\python37.zip',
'C:\\Program Files (x86)\\Microsoft Visual
Studio\\Shared\\Python37_64\\DLLs',
'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\lib',
'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64',
'C:\\Users\\admin\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Program Files (x86)\\Microsoft Visual '
'Studio\\Shared\\Python37_64\\lib\\site-packages']
Server time: Thu, 14 Jan 2021 19:15:32 +0000
It was working before but suddenly not working now. Here is my views.py
from django.shortcuts import render
# from django.http import HttpResponse
# from django.template import RequestContext, loader
# from django.template import Context
def index(request):
"""Placeholder index view"""
print('XXXX')
return render(request, 'hello_world/index.html')
#return HttpResponse('Hello, World!')
def test(request):
context = {'foo': 'bar'}
return render(request, 'hello_world/index.html', context)
The error is in line return render(request, 'hello_world/index.html') but when I change it to return HttpResponse('Hello, World!') it works fine.
My html file is very simple index.html
<h3> MY DJANGO APP</h3>
The html file is also in the correct folder templates/hello_world/index.html
settings
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': False,
'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.contrib.sessions'
],
},
},
]

django.contrib.sessions is not a callable object, hence it's not a valid context processor.
In fact, it's an app and, so, it should be in your INSTALLED_APPS list, not in the TEMPALTES context_processors list. Removing it from there should fix this issue.
Why is this happening?
The exception mentions that it is happening in django/template/context.py line 246 (in Django v3.0.11). If you see the source code at line 246, you can see that at this line Django is running the registered template context processors. Since, django.contrib.sessions is not a callable object, but a module, you get this exception message: 'module' object is not callable.

Related

Vscode python file runs fine but ModuleNotFoundError is thrown when code-runner is used

Hello I have the following directory structure for my project in vscode:
--- my_programs/----|
|--my_code/----|
|__tests/
|
|__libs/my_package/classes.py
|
|__main/main.py
When I run main.py in the vscode terminal it runs fine. As soon as I run it using "Run Code" (which is an extension) it complains about the following:
`
Running] /Users/username/my_programs/venv/bin/python -u "/Users/username/my_programs/my_code/main/main.py"
Traceback (most recent call last):
File "/Users/username/my_programs/my_code/main/main.py", line 2, in <module>
from libs.my_package.classes import MyClass
ModuleNotFoundError: No module named 'libs'
`
main.py looks like this:
import os
from libs.my_package.classes import MyClass
dir_path = os.path.dirname(os.path.realpath(__file__))
print (dir_path)
cwd = os.getcwd()
print(cwd)
os.chdir(dir_path)
cwd = os.getcwd()
print (cwd)
m = MyClass("Hello Hello")
print(m)
My settings.json looks like the following:
{
"terminal.integrated.env.osx": {"PYTHONPATH": "${workspaceFolder}/my_code"},
"python.envFile": "${workspaceFolder}/.vscode/env",
"python.analysis.extraPaths": [
"my_programs",
],
"python.testing.pytestArgs": [
"my_code"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"python.testing.cwd": "${workspaceFolder}",
"python.terminal.activateEnvironment": true,
"python.terminal.activateEnvInCurrentTerminal": true,
"code-runner.fileDirectoryAsCwd": false,
"code-runner.executorMap":
{
"python": "$pythonPath -u $fullFileName"
},
}
Why does it work when I click "Run Python File" and not when I do "Run Code"? FYI, it also works manually from the terminal.

Django Content Management System [duplicate]

My setup is Windows 10, Python 3.7, Apache 2.4/mod_wsgi. When I add this enctype="multipart/form-data" in my form (just by adding this attribute, only -- no files are attached to the form) I get this error when submitting:
Django Version: 1.8.5
Exception Type: RuntimeError
Exception Value: generator raised StopIteration
Exception Location: c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\multipartparser.py in read, line 337
Python Executable: C:\Apache24\bin\httpd.exe
Python Version: 3.7.3
My Django code is this:
elif request.method == "POST":
rid = request.POST.get("recipe", "")
title = request.POST.get("title")
content = request.POST.get("content")
tag_names = request.POST.getlist("tags")
image = request.FILES.get("image")
if rid:
recipe = get_object_or_404(FoodRecipe, pk=rid)
else:
recipe = FoodRecipe.objects.create(title=title)
recipe.content = content
recipe.title = title
if image:
recipe.featured = image
for tn in tag_names:
tag, cr = Tag.objects.get_or_create(
name=tn
)
recipe.tags.add(tag)
recipe.save()
And this is full traceback:
Environment:
Request Method: POST
Request URL: http://192.168.1.250/recipes/add/
Django Version: 1.8.5
Python Version: 3.7.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tinymce',
'sekizai',
'sorl.thumbnail',
'recipes',
'guides',
'inbox',
'appdata',
'account',
'customer',
'core')
Installed Middleware:
('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',
'django.middleware.security.SecurityMiddleware',
'account.middleware.PasswordChangeMiddleware.PasswordChangeMiddleware')
Traceback:
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\core\handlers\base.py" in get_response
125. response = middleware_method(request, callback, callback_args, callback_kwargs)
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\middleware\csrf.py" in process_view
174. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\core\handlers\wsgi.py" in _get_post
137. self._load_post_and_files()
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\request.py" in _load_post_and_files
260. self._post, self._files = self.parse_file_upload(self.META, data)
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\request.py" in parse_file_upload
225. return parser.parse()
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\multipartparser.py" in parse
149. for item_type, meta_data, field_stream in Parser(stream, self._boundary):
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\multipartparser.py" in __iter__
628. yield parse_boundary_stream(sub_stream, 1024)
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\multipartparser.py" in parse_boundary_stream
567. chunk = stream.read(max_header_size)
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\multipartparser.py" in read
337. out = b''.join(parts())
Exception Type: RuntimeError at /recipes/add/
Exception Value: generator raised StopIteration
Any ideas what is going wrong?
PS: Same django application worked fine in Linux/Nginx/Gunicorn/Python2.7 setup. So, I guess it must some misconfiguration between Django/Python/Apache.
Your Django is very old and you need to update. This is a Python 3.7 compatibility problem that the Django devs already fixed four years ago, back when it was just a PendingDeprecationWarning on Python 3.5.
In fact, you are on the very last Django version that doesn't have the fix. Even 1.8.6 has the fix.

How to execute locally installed Node.js application by child_process.spawn()?

I want to execute the Electron application by child_process.spawn:
import ChildProcess, {ChildProcess as ChildProcess__type} from 'child_process';
const childProcess: ChildProcess__type = ChildProcess.spawn(
'electron',
['ProjectInitializer__ElectronMain.js'],
{ cwd: __dirname } // current project root
);
I got Error: spawn electron ENOENT error. Electron has been installed locally, AFAIK is the good practice. Also, electron ProjectInitializer__ElectronMain.js works, it to execute this console command from my project directory.
Following frequently up-voted ENOENT error debugging guidance, I got the cause: there is no directory among process.env.PATH, which includes electron.
I know about PATH variable not much, so I can not answer what must be in this variable and what is not. But what I want to ask is: how to execute locally installed (in node_modules) Node.js applications (like electron)?
By the way, execa which is known as improved child_process runs electron without errors (update: version 2.x.x already do not runs):
import executeExternalCommand, { ExecaReturnValue } from 'execa';
try {
await executeExternalCommand(
'electron',
['ProjectInitializer__ElectronMain.js'],
{ cwd: __dirname }
);
} catch (error) {
console.error(error);
}
Somehow, thanks to { cwd: __dirname }, the execa v 1.x.x knows, where should to find the electron. Unfortunately, execa has too small community and small documentations, so stopped to use it.
Additional information
How I run this Node.js script which has the spawn parameter
By command my-library init which I created.
In package.json:
"bin": {
"my-library": "bin/my-library"
}
In bin/my-library (no filename extension):
#!/usr/bin/env node
require('../CLI').interpretConsoleCommandAndExecute(process.argv);
In CLI.js I parse the console command, and if it is the my-library init, I'll try to execute
const childProcess: ChildProcess__type = ChildProcess.spawn(
'electron',
[ 'ProjectInitializer__ElectronMain.js' ],
{ cwd: __dirname }
);
console.log(process.env) output
Below output is for PhpStorm build-in console, however in other consoles, e. g. in cmder, output is different.
{ FPS_BROWSER_APP_PROFILE_STRING: 'Internet Explorer',
CommonProgramFiles: 'C:\\Program Files\\Common Files',
PROMPT: '$P$G',
SESSIONNAME: 'Console',
COMPUTERNAME: 'MSI',
OneDriveConsumer: 'D:\\OneDrive',
__INTELLIJ_COMMAND_HISTFILE__:
'C:\\Users\\i\\.PhpStorm2019.1\\config\\terminal\\history\\history-34',
SystemDrive: 'C:',
NUMBER_OF_PROCESSORS: '12',
LOGONSERVER: '\\\\MSI',
TEMP: 'C:\\Users\\i\\AppData\\Local\\Temp',
TMP: 'C:\\Users\\i\\AppData\\Local\\Temp',
HOMEPATH: '\\Users\\i',
PATHEXT: '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JSE;.WSF;.WSH;.MSC',
USERNAME: 'i',
ProgramFiles: 'C:\\Program Files',
USERDOMAIN_ROAMINGPROFILE: 'MSI',
LOCALAPPDATA: 'C:\\Users\\i\\AppData\\Local',
TERMINAL_EMULATOR: 'JetBrains-JediTerm',
PROCESSOR_IDENTIFIER: 'Intel64 Family 6 Model 158 Stepping 10, GenuineIntel',
DriverData: 'C:\\Windows\\System32\\Drivers\\DriverData',
APPDATA: 'C:\\Users\\i\\AppData\\Roaming',
ALLUSERSPROFILE: 'C:\\ProgramData',
USERDOMAIN: 'MSI',
OS: 'Windows_NT',
PROCESSOR_LEVEL: '6',
ProgramData: 'C:\\ProgramData',
ComSpec: 'C:\\Windows\\system32\\cmd.exe',
PROCESSOR_ARCHITECTURE: 'AMD64',
FPS_BROWSER_USER_PROFILE_STRING: 'Default',
SystemRoot: 'C:\\Windows',
PROCESSOR_REVISION: '9e0a',
OneDrive: 'D:\\OneDrive',
PSModulePath:
'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules',
PATH:
'D:\\PhpStorm\\InHouseDevelopment\\my-library\\node_modules\\.bin;C:\\ProgramData\\DockerDesktop\\version-bin;C:\\Program Files\\Docker\\Docker\\Resources\\bin;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\iCLS\\;C:\\Program Files
\\Intel\\Intel(R) Management Engine Components\\iCLS\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Pro
gram Files\\Intel\\WiFi\\bin\\;C:\\Program Files\\Common Files\\Intel\\WirelessCommon\\;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files (x86)\\Intel\\I
ntel(R) Management Engine Components\\IPT;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program Files (x86)\\Common Files\\Acronis\\VirtualFile\\;C:\\Program Files (x86)\\Common Files\\Acronis\\VirtualFile64\\;C:\\Program Files (x86)\\Com
mon Files\\Acronis\\FileProtector\\;C:\\Program Files (x86)\\Common Files\\Acronis\\FileProtector64\\;C:\\Program Files (x86)\\Common Files\\Acronis\\SnapAPI\\;C:\\Program Files\\nodejs\\;C:\\Program Files\\Git\\cmd;C:\\Program Files (x86)\\Yarn\\bin\\;C:\\Users\\t
okug\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\i\\AppData\\Roaming\\npm;C:\\Users\\i\\AppData\\Local\\Yarn\\bin;C:\\texlive\\2019\\bin\\win32',
'ProgramFiles(x86)': 'C:\\Program Files (x86)',
USERPROFILE: 'C:\\Users\\i',
windir: 'C:\\Windows',
ProgramW6432: 'C:\\Program Files',
configsetroot: 'C:\\Windows\\ConfigSetRoot',
'CommonProgramFiles(x86)': 'C:\\Program Files (x86)\\Common Files',
PUBLIC: 'C:\\Users\\Public',
HOMEDRIVE: 'C:',
CommonProgramW6432: 'C:\\Program Files\\Common Files' }
Trying to execute ChildProcess.spawn('env')
In Php Strorm console, it causes familiar Error: spawn env ENOENT.
As discussed in the chat, the error you are getting is usually caused by the fact that the executable you are trying to run is not available
Now there are multiple reasons the executable may not be available
The executable is not there at all anywhere on the system
The executable is there but not in the folders defined by system's PATH variable
The executable is there in the current directory but the directory context in which the process is being run is different
To fix #1 and #2 you just install the executable globally in system PATH
For fixing #3 you can do two things. Add the path for the current directory ({ cwd: __dirname}) and also a relative path to executable
const childProcess: ChildProcess__type = ChildProcess.spawn(
Path.resolve(__dirname, 'node_modules/.bin/electron'),
[ Path.resolve(__dirname, 'ProjectInitializer__ElectronMain.js') ],
{ cwd: __dirname}
);
or
const childProcess: ChildProcess__type = ChildProcess.spawn(
'./node_modules/.bin/electron'),
[ Path.resolve(__dirname, 'ProjectInitializer__ElectronMain.js') ],
{ cwd: __dirname}
);
or
const childProcess: ChildProcess__type = ChildProcess.spawn(
'node_modules/.bin/electron',
[ './ProjectInitializer__ElectronMain.js' ],
{ cwd: __dirname}
);
In case you decide to override the PATH environment variable you can do it passing the env parameters with more values
const childProcess: ChildProcess__type = ChildProcess.spawn(
'node_modules/.bin/electron',
[ './ProjectInitializer__ElectronMain.js' ],
{ cwd: __dirname, env: {....}}
);
You can use the existing environment variables from process.env and then update the same, and pass it to env parameter
it’s likely that you need to specify the full path to the electron command, since it isn’t on your path.
If you are running your script from your project root, electron is probably at in ./node_modules/.bin/electron, if they packaged up the app to be run that way.
I would guess that your alternative library checks node_modules by default.
The alternative would be to ensure electron is in your path, but that requires updating your system configuration, which it would be weird for a library to do.
Edit: example of call with path:
const childProcess: ChildProcess__type = ChildProcess.spawn(
'node_modules/.bin/electron',
[ 'ProjectInitializer__ElectronMain.js' ],
{ cwd: __dirname }
);
I'd also add some dumb logging on the process, so you know why the process failed:
function log(data) {
console.log("" + data)
}
child_process.stdout.on('data', log)
child_process.stderr.on('data', log)
child_process.on('close', log)

Error on deploying Python app to AWS Lambda

I have built a Python-Tornado app and am trying to deploy it to AWS Lambda using zappa. But, I am getting an error Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code.
My folder structure inside the root folder is :
├── amortization.py
├── config.py
├── dmi-amort-dev-1557138776.zip
├── main.py
├── requirements.txt
├── venv
│   ├── bin
│  
└── zappa_settings.json
zappa deploy dev gives me :
Calling deploy for stage dev..
Downloading and installing dependencies..
- pandas==0.24.2: Using locally cached manylinux wheel
- numpy==1.16.3: Using locally cached manylinux wheel
- sqlite==python3: Using precompiled lambda package
Packaging project as zip.
Uploading dmi-amort-dev-1557143681.zip (30.8MiB)..
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 32.3M/32.3M [00:19<00:00, 1.94MB/s]
Scheduling..
Scheduled dmi-amort-dev-zappa-keep-warm-handler.keep_warm_callback with expression rate(4 minutes)!
Uploading dmi-amort-dev-template-1557143718.json (1.5KiB)..
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1.56K/1.56K [00:00<00:00, 10.6KB/s]
Waiting for stack dmi-amort-dev to create (this can take a bit)..
75%|█████████████████████████████████████████████████████████████████████████████████████████████████████▎ | 3/4 [00:09<00:04, 5.00s/res]
Deploying API Gateway..
Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code.
zappa tail gives me
Traceback (most recent call last):
File "/var/task/handler.py", line 602, in lambda_handler
return LambdaHandler.lambda_handler(event, context)
File "/var/task/handler.py", line 245, in lambda_handler
handler = cls()
File "/var/task/handler.py", line 142, in __init__
wsgi_app_function = getattr(self.app_module, self.settings.APP_FUNCTION)
AttributeError: module 'main' has no attribute 'app'
zappa_settings.json:
{
"dev": {
"app_function": "main.app",
"aws_region": "ap-south-1",
"profile_name": "default",
"project_name": "dmi-amort",
"runtime": "python3.6",
"s3_bucket": "zappa-mekp457ye",
"manage_roles": false,
"role_name": "lambda-role",
}
}
main.py:
import tornado.web
from tornado.ioloop import IOLoop
from tornado.web import MissingArgumentError
from config import get_arguments
from amortization import get_amort_schedule
class MainHandler(tornado.web.RequestHandler):
def prepare(self):
"""Checking if all the required parameters are present."""
if self.request.method != 'POST':
self.write_error(status_code=405, message="Method not allowed")
return
self.parameters = dict()
for key in get_arguments():
try:
self.parameters[key] = self.get_argument(key)
except MissingArgumentError:
self.write_error(status_code=400,
message="Missing Argument(s)")
return
# checking if 'label' is provided
if 'label' in self.request.arguments.keys():
self.parameters['label'] = self.get_argument('label')
# Set up response dictionary.
self.response = dict()
def get(self, *args, **kwargs):
self.write_error(status_code=405, message="Method not allowed")
def post(self, *args, **kwargs):
"""Executes the main logic part."""
self.response = get_amort_schedule(self.parameters)
self.write_json()
def set_default_headers(self):
"""Sets content-type as 'application/json' for response as JSON."""
self.set_header('Content-Type', 'application/json')
def write_error(self, status_code, **kwargs):
"""Invokes when error occurs in processing the request."""
if 'message' not in kwargs:
if status_code == 405:
kwargs['message'] = 'Invalid HTTP method.'
else:
kwargs['message'] = 'Unknown error.'
kwargs["error"] = True
self.set_status(status_code=status_code)
self.response = dict(kwargs)
self.write_json()
def write_json(self):
"""Responsible for writing the response."""
if "status" in self.response:
self.set_status(self.response.get("status"))
self.set_default_headers()
self.write(self.response)
self.finish()
def main():
app = tornado.web.Application([
(r'/', MainHandler),
], debug=True)
# server = HTTPServer(app)
# server.bind(8888)
# server.start(0)
app.listen()
# app.run(host='0.0.0.0')
IOLoop.current().start()
if __name__ == '__main__':
main()
What is the mistake here and how can I fix it?
It looks like the deployment is succeeding, but when Zappa checks to see if the code is working, the return code is 502, which suggests that the lambda function is failing to run in the lambda environment.
Taking a look at the logs, the critical line is:
AttributeError: module 'main' has no attribute 'app'
And this is true, if we look at your code, at no point do you expose an attribute called app in main.py.
I'm not experienced with Tornado, but I suspect that if you move the declaration of app out of the main() function and into the root scope, then the handler should succeed.
For example:
# rest of the file...
self.finish()
app = tornado.web.Application([
(r'/', MainHandler),
], debug=True)
app.listen()
def main():
IOLoop.current().start()
if __name__ == '__main__':
main()

TemplateDoesNotExist at /search/ in Django 2.0.2

when I try to execute the function, I am getting (TemplateDoesNotExist at /search/)
my templates folder is located at C:\Users\Rafik\Documents\myproject\env_mysite\Scripts\mysie\books\templates
python code is running fine but it says TemplateDoesNotExist
views.py:
def search(request):
error = False
if 'q' in request.GET:
q = request.GET['q']
if not q:
error = True
elif len(q) > 20:
error = True
else:
books = Book.objects.filter(title__icontains=q)
return render(request, 'search_results.html', {'books': books, 'query': q})
return render(request, 'search_form.html', {'error': error})
apps/urls.py:
from django.conf.urls import url
from books import views
urlpatterns = [
url(r'^search-form/$', views.search_form),
url(r'^search/$', views.search)
]
TEMPLATE 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',
],
},
},
]
I am new to stackoverflow as an author, so please excuse me for not using the appropriate markup here. I run into the same error when working through the Django 2.0 tutorial (more specifically: in Tutorial03, after switching from loader.get_template() to shortcuts.render()). The following solution finally proved to work for me:
In the TEMPLATES section of my settings.py, DIRS remains an empty list and APP_DIRS is set to True.
In the render() statement, there is no path portion when specifying the template, just e.g. render(request, 'index.html', context)
the template file must directly be located in the app/templates directory (not in /app/templates/app)
My enviroment is Django 2.0.2 with CPython 3.6.4 under Windows 10 (and cygwin). Hope this helps.

Resources