TemplateDoesNotExist at /search/ in Django 2.0.2 - python-3.x

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.

Related

Why is #pytest.fixture passed as an argument to tests but not used

Below is a test file for the Streamlink library. I was reading the test files to understand how testing is done and found a confusing set up for the tests. The test set up a series of #pytest.fixtures to help with testing. The assert_live fixture below is defined and passed into some tests, but never called at all. I dont think this is a mistake because a similar pattern is found throughout the file. I read the docs for fixtures but couldn't find anything that mentions this functionality. I got excited when they talked about using yeild inside a fixture but that turned not to touch on the subject either. Google was even less helpful. I am at a loss, but I am very interested in contributing to this library and need to understand how it works and how they test. Test is at the bottom of the code below. Thank you in advance!
# Other fixtures for context/continuity
#pytest.fixture
def mocker(self):
# The built-in requests_mock fixture is bad when trying to reference the following constants or classes
with requests_mock.Mocker() as mocker:
mocker.register_uri(requests_mock.ANY, requests_mock.ANY, exc=requests_mock.exceptions.InvalidRequest)
yield mocker
#pytest.fixture
def mock(self, request, mocker: requests_mock.Mocker):
mock = mocker.post("https://gql.twitch.tv/gql", **getattr(request, "param", {"json": {}}))
yield mock
assert mock.called_once
payload = mock.last_request.json() # type: ignore[union-attr]
assert tuple(sorted(payload.keys())) == ("extensions", "operationName", "variables")
assert payload.get("operationName") == "PlaybackAccessToken"
assert payload.get("extensions") == {
"persistedQuery": {
"sha256Hash": "0828119ded1c13477966434e15800ff57ddacf13ba1911c129dc2200705b0712",
"version": 1,
},
}
# The confusing fixture
#pytest.fixture
def assert_live(self, mock):
yield
assert mock.last_request.json().get("variables") == { # type: ignore[union-attr]
"isLive": True,
"isVod": False,
"login": "channelname",
"vodID": "",
"playerType": "embed",
}
# The confusing test
# note that assert_live is passed as an arg but is not actually used.
#pytest.mark.parametrize("plugin,mock", [
(
[("api-header", [("Authorization", "OAuth invalid-token")])],
{
"status_code": 401,
"json": {"error": "Unauthorized", "status": 401, "message": "The \"Authorization\" token is invalid."},
},
),
], indirect=True)
def test_auth_failure(self, caplog: pytest.LogCaptureFixture, plugin: Twitch, mock: requests_mock.Mocker, assert_live):
with pytest.raises(NoStreamsError) as cm:
plugin._access_token(True, "channelname")
assert str(cm.value) == "No streams found on this URL: https://twitch.tv/channelname"
assert mock.last_request._request.headers["Authorization"] == "OAuth invalid-token" # type: ignore[union-attr]
assert [(record.levelname, record.module, record.message) for record in caplog.records] == [
("error", "twitch", "Unauthorized: The \"Authorization\" token is invalid."),
]

Assign a simple HTML site with django

I want to assign/add a simple static HTML site to my django site. I know that's not what django is for but at the beginning I just want to create a simple site with a href to the other directories on the project.
For e.g.
index.html
<html>
<head></head>
<body>
anzeige<br />
Speiseplan <br />
Menu1<br />
Menu2<br />
Menu3<br />
</body>
</html>
Now I want to add this site to urls.py. I read that it shoud be possible with TemplateView.
I already tried this:
urlpatterns = [
path('', TemplateView.as_view(template_name="/templates/speiseleitsystem/index.html")),
path('speiseplan/', views.speiseplan_Anzeige, name='speiseplan_Anzeige'),
path('speiseplanEdit/', views.speiseplan_Eintragen, name='speiseplan_Eintragen'),
path('menu1/', views.speiseplan_menu1, name='speiseplan_menu1'),
path('menu2/', views.speiseplan_Anzeige, name='speiseplan_menu2'),
path('menu3/', views.speiseplan_Anzeige, name='speiseplan_menu3'),
]
My error code:
TemplateDoesNotExist at /
/templates/speiseleitsystem/index.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.6
Exception Type: TemplateDoesNotExist
Exception Value:
/templates/speiseleitsystem/index.html
Exception Location: C:\Users\xxxxx\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader.py, line 47, in select_template
Python Executable: C:\Users\xxxx\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.0
Python Path:
['C:\\Users\\xxxx\\Documents\\GitHub\\speiseplan\\speiseplan',
'C:\\Users\\xxxx\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\xxx\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\xxx\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\xxx\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\xxxx\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']
Server time: Thu, 18 Feb 2021 15:15:06 +0000
Did I missed something?
Depending on your project structure and settings, this might work:
In your url patterns, you have this line:
path('', TemplateView.as_view(template_name="/templates/speiseleitsystem/index.html")),
Change it to :
path('', TemplateView.as_view(template_name="speiseleitsystem/index.html")),
Django already knows that it has to look inside templates folder, given that your structure is something like this:
-project
- speiseleitsystem
\templates
\speiseleitsystem
\index.html
Remove /template/ from the url pattern and django will look in the correct place.
Currently it is looking for this directory:
project/speiseleitsystem/templates/speiseleitsystem/templates/speiseleitsystem/index.html
Which is surely not what you want it.
In case anyone will struggle with the same problem, the solution is a mix of all answers here.
Add the template directory into the setting.py inside TEMPLATES and there DIRS
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['speiseleitsystem/templates'],
'APP_DIRS': True,
'OPTIONS': {
],
},
},
]`
Note: Depending on the project structure only 'templates' is needed in DIRS
Add the right path to urls.py (as MoPo mentioned)
urlpatterns = [
path('', TemplateView.as_view(template_name="speiseleitsystem/index.html")),
]
Because of the template directory in setting.py templates/... is not needed here.

TypeError: 'module' object is not callable Django 3 render function

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.

GAE files blocked due to mimetype/unknown url handler type for js files with multiple .'s

I've been hung up on deploying my React/Django app to GAE for the last two days and I think I've isolated the issue, but I've been unable to come up with a solution that works. When I first deployed I was running into issues with mimetypes with each of my JS and CSS files embedded in my index.html being blocked with error messages like these leading me to believe it found the files but didn't handle them correctly:
(file) was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
My understanding from browsing SO and doing research was that GAE was treating these as html files and not executing them properly. I started playing with the .yaml to enforce mime types due to some settings I saw in the references for GAE and now I can't deploy and get error message:
ERROR: (gcloud.app.deploy) An error occurred while parsing file: [(mysite)\app.yaml]
Unknown url handler type.
<URLMap
static_files=None
upload=None
application_readable=None
static_dir=None
mime_type=text/css
expiration=None
require_matching_file=None
http_headers=None
position=None
api_endpoint=None
redirect_http_response_code=None
url=/static/css\.css
login=optional
auth_fail_action=redirect
secure=default
script=None
>
in "(mysite)/app.yaml", line 8, column 1
I've been playing around with the files in the browser and I've found that I get 404 errors when I try to pull up the files despite knowing that they're in the directory. IE navigating here: https://acptconstruction.appspot.com/backend/static/js/2.738f0ca9.chunk.js yields a 404, but I can see it with the exact filename in the directory. Because of that and the error message on deployment, I think that maybe GAE is having trouble parsing the filenames because of all of the periods? The filenames were built when I ran npm run-scripts build after I was finished with the front end app, but regardless, I tried to deploy copying that file to homepage.js and including using that exact filename with the path without success.
I don't know if I was on a better track with the first yaml file, where it could "find" them (I think) and not grock them or with the second yaml where they couldn't be found? The issue might be as simple as copying all the js files and changing their names to like homepage.js and homepage2.js but I am nervous that I might break everything if I go down that path. Any help is appreciated!
Files:
Originally, my app.yaml file looked like this:
runtime: python38
handlers:
- url: /static
static_dir: static/
- url: /.*
script: auto
Updated YAML that gives the deployment errors:
runtime: python38
handlers:
- url: /static/css/(.*)
mime_type: text/css
- url: /static/js/(.*)
mime_type: text/javascript
index.html:
<!doctype html><html lang="en" style="background-color:#f1f1f1"><head><base href="/"> <meta charset="utf-8"/><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="ACPT Construction"/><link rel="manifest" href="/manifest.json"/><title>ACPT Construction</title><link type="text/css" href="/backend/static/css/2.89e89512.chunk.css" rel="stylesheet"><link type="text/css" href="/backend/static/css/main.cfd2a7ed.chunk.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root" style="min-height:1000px"></div><script>!function(e){function t(t){for(var n,c,i=t[0],l=t[1],a=t[2],f=0,s=[];f<i.length;f++)c=i[f],Object.prototype.hasOwnProperty.call(o,c)&&o[c]&&s.push(o[c][0]),o[c]=0;for(n in l)Object.prototype.hasOwnProperty.call(l,n)&&(e[n]=l[n]);for(p&&p(t);s.length;)s.shift()();return u.push.apply(u,a||[]),r()}function r(){for(var e,t=0;t<u.length;t++){for(var r=u[t],n=!0,i=1;i<r.length;i++){var l=r[i];0!==o[l]&&(n=!1)}n&&(u.splice(t--,1),e=c(c.s=r[0]))}return e}var n={},o={1:0},u=[];function c(t){if(n[t])return n[t].exports;var r=n[t]={i:t,l:!1,exports:{}};return e[t].call(r.exports,r,r.exports,c),r.l=!0,r.exports}c.m=e,c.c=n,c.d=function(e,t,r){c.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},c.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.t=function(e,t){if(1&t&&(e=c(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(c.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)c.d(r,n,function(t){return e[t]}.bind(null,n));return r},c.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return c.d(t,"a",t),t},c.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},c.p="/";var i=this.webpackJsonpacptconstruction=this.webpackJsonpacptconstruction||[],l=i.push.bind(i);i.push=t,i=i.slice();for(var a=0;a<i.length;a++)t(i[a]);var p=l;r()}([])</script><script type="application/javascript" src="/backend/static/js/2.738f0ca9.chunk.js"></script><script type="application/javascript" src="/backend/static/js/main.b160e3e4.chunk.js"></script></body></html>
File structure:
acptconstruction
backend
settings.py
manage.py (command to run server is python manage.py runserver)
backend
views.py (heres where index.html gets called)
urls.py (url structure)
acptconstruction (front end)
build
index.html
manifest.json
app.yaml
static
css
js
media
settings.py:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/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 = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'emailcontactform',
'corsheaders'
]
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'corsheaders.middleware.CorsMiddleware',
'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 = 'backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'acptconstruction')],
'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 = 'backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/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.11/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.11/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.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'acptconstruction', 'build', 'static'),
]
if DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'backend','/static')
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT =
EMAIL_HOST_USER =
EMAIL_HOST_PASSWORD =
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000',
'http://localhost:8000',
'http://localhost:8080',
]
https://your_app.appspot.com/backend/static/js/2.738f0ca9.chunk.js does not match any pattern in your app.yaml. Either get rid of the /backend/ part of the url, or add the handler to your app.yaml:
handlers:
- url: /static/css
static_dir: static/css
- url: /backend/static/css
static_dir: static/css
- url: /static/js
static_dir: static/js
- url: /backend/static/js
static_dir: static/js
And the mime_type error you saw was probably due to your tags in the template.html file. The proper tags are:
<link rel="stylesheet" href="styles.css">
or:
<link rel="stylesheet" type="text/css" href="styles.css">
You don't want to put text/html in those tags.

Create Stack Instances Parameter Issue

I'm creating stack instance, using python boto3 SDK. According to the documentation I should be able to use ParameterOverrides but I'm getting following error..
botocore.exceptions.ParamValidationError: Parameter validation failed:
Unknown parameter in input: "ParameterOverrides", must be one of: StackSetName, Accounts, Regions, OperationPreferences, OperationId
Environment :
aws-cli/1.11.172 Python/2.7.14 botocore/1.7.30
imports used
import boto3
import botocore
Following is the code
try:
stackset_instance_response = stackset_client.create_stack_instances(
StackSetName=cloudtrail_stackset_name,
Accounts=[
account_id
],
Regions=[
stack_region
],
OperationPreferences={
'RegionOrder': [
stack_region
],
'FailureToleranceCount': 0,
'MaxConcurrentCount': 1
},
ParameterOverrides=[
{
'ParameterKey': 'CloudtrailBucket',
'ParameterValue': 'test-bucket'
},
{
'ParameterKey': 'Environment',
'ParameterValue': 'SANDBOX'
},
{
'ParameterKey': 'IsCloudTrailEnabled',
'ParameterValue': 'NO'
}
]
)
print("Stackset create Response : " + str(stackset_instance_response))
operation_id = stackset_instance_response['OperationId']
print (operation_id)
except botocore.exceptions.ClientError as e:
print("Stackset creation error : " + str(e))
I'm not sure where I'm doing wrong, any help would be greatly appreciated.
Thank you.
1.8.0 is the first version of Botocore that has parameteroverrides defined.
https://github.com/boto/botocore/blob/1.8.0/botocore/data/cloudformation/2010-05-15/service-2.json#L1087-L1090
1.7.30 doesn't have that defined. https://github.com/boto/botocore/blob/1.7.30/botocore/data/cloudformation/2010-05-15/service-2.json

Resources