Assign a simple HTML site with django - python-3.x

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.

Related

Name parameter not recognized in Django

Everytime i get Page not found
i try renaming my views.py, I did my makemigrations and migrate, and nothing happened
Hi, I am working on this python project and I can't get the name parameters to work in my URLs. I have tried everything but my code is not recognizing them.
urlpatterns = [
path('estudiantes/', listar_estudiantes, name="listar_alumnos"),
path('profesores/', listar_profesores, name="listar_profesores"),
path('', inicio, name="inicio"),
path('admin/', admin.site.urls),
path('curso/', listar_curso, name="listar_curso"),
path('enviar-curso/', crear_curso, name="crear_curso"),
path('buscar-curso/', buscar_curso, name="buscar_curso"),
path('curso/<int:id>/', ver_curso, name="ver_curso"),
]

Django href link not routing to correct url

The links within my pages/templates/base.html which are used for a header template results in 404 error. The pages load correctly when manually written 'http://127.0.0.1:8000' 'http://127.0.0.1:8000/about/'.
I am using class based views and following chapter 3 of Django for beginners (William Vincent).
pages/templates/base.html:
<header>
Home |
About
</header>
pages/urls.py:
from django.urls import path
from .views import HomePageView, AboutPageView
urlpatterns = [
path("", HomePageView.as_view(), name="home"),
path("about/", AboutPageView.as_view(), name="about"),
]
portfolio/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("pages.urls")),
]
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pages.apps.PagesConfig',
]
pages/views.py:
from django.views.generic import TemplateView
# Create your views here.
from django.http import HttpResponse
class HomePageView(TemplateView):
template_name = 'home.html'
class AboutPageView(TemplateView):
template_name = "about.html"
The error is as follows:
Using the URLconf defined in portfolio.urls, Django tried these URL patterns, in this order:
admin/
[name='home']
about/ [name='about']
The current path, about/{% url 'about' %, didn’t match any of these.
Terminal error:
Not Found: /{% url 'about' %
[26/Oct/2022 11:40:02] "GET /%7B%%20url%20'about'%20% HTTP/1.1" 404 2497
I think the issue lies in pages/urls.py, as if click the 'home' link from 'http://127.0.0.1:8000/about/' the url is 'http://127.0.0.1:8000/about/%7B%%20url%20'home'%20%'. I've tried to remove the "about/" from " path("about/", AboutPageView.as_view(), name="about"),
"
I am also not sure whether the href tags have been written correctly. I have looked at this and this but can't figure it out. Thanks.
{% url 'about' % <- you need to close it properly.

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.

Durandal.js optimizer generating empty main-built.js

I am trying to optimize my Durandal app but the main-built.js is blank.
I have tried running node r.js -o app.build.js and this threw an error saying that it could not find a file. I added these paths in my main.js file and each individual error went away. However, now the command above just exits with "Tracing dependencies for: durnadal/amd/almond.custom" and the file is still blank.
Question: Which libraries need to go into the paths below? It seems to the external libraries that I use in my index.html and it needs the exact file name?
require.config({
paths: {
"text": "durandal/amd/text",
"breeze": "lib/breeze/breeze.min",
"knockout": "lib/knockout/knockout.mapping-latest",
}
});
When I run Optimizer.exe in the Durandal AMD folder main-built.js is blank. This is the app.build.js file that is generated - any help appreciated on how to get more verbose logging with Almond. I have tried optimizer -verbose true with no luck.
{
"name": "durandal/amd/almond-custom",
"inlineText": true,
"stubModules": [
"durandal/amd/text"
],
"paths": {
"text": "durandal/amd/text"
},
"baseUrl": "C:\\DNNDev.me\\DesktopModules\\Framework.App\\App",
"mainConfigFile": "C:\\DNNDev.me\\DesktopModules\\Framework.App\\App\\main.js",
"include": [
"text!about.html",
"about",
"appNavigation",
"config",
"text!dareAdd.html",
"dareAdd",
"text!dareDetail.html",
"dareDetail",
"text!dareList.html",
"dareList",
"text!dareListItem.html",
"dataContext",
"dataService",
"dataServiceHelper",
"enums",
"errorWatcher",
"text!home.html",
"home",
"text!index.html",
"text!indextopcoat.html",
"indextopcoat",
"text!kendoIndex.html",
"text!loader.html",
"logger",
"text!login.html",
"login",
"main-built",
"main",
"text!menu.html",
"model",
"text!navbar.html",
"text!notifyOfError.html",
"notifyOfError",
"text!privacy.html",
"privacy",
"text!profile.html",
"profile",
"text!shell.html",
"shell",
"text!signup.html",
"signup",
"text!testpage.html",
"testpage",
"uiutilities",
"userState",
"viewModelHelper",
"text!walkthrough.html",
"walkthrough",
"widgetService",
"css/telerik/js/kendo.dataviz.min",
"css/topcoat/js/hello",
"css/topcoat/js/hello.min",
"css/topcoat/js/index",
"css/topcoat/lib/hello",
"css/topcoat/lib/vendor/ender.min",
"css/topcoat/lib/vendor/fastclick",
"durandal/app",
"durandal/composition",
"durandal/events",
"durandal/http",
"text!durandal/messageBox.html",
"durandal/messageBox",
"durandal/modalDialog",
"durandal/system",
"durandal/viewEngine",
"durandal/viewLocator",
"durandal/viewModel",
"durandal/viewModelBinder",
"durandal/widget",
"durandal/plugins/router",
"durandal/transitions/entrance",
"js/cordova",
"js/facebookscript",
"lib/bootstrap/bootstrap",
"lib/bootstrap/bootstrap.min",
"lib/breeze/breeze.debug",
"lib/breeze/breeze.intellisense",
"lib/breeze/breeze.min",
"lib/breeze/q",
"lib/breeze/q.min",
"lib/jquery/jquery-2.0.3.intellisense",
"lib/jquery/jquery-2.0.3",
"lib/jquery/jquery-2.0.3.min",
"lib/knockout/knockout-2.3.0.debug",
"lib/knockout/knockout-2.3.0",
"lib/knockout/knockout.mapping-latest.debug",
"lib/knockout/knockout.mapping-latest",
"lib/knockout/knockout.validation.debug",
"lib/knockout/knockout.validation",
"lib/moment/moment",
"lib/moment/moment.min",
"lib/ratchet/ratchet",
"lib/sammy/sammy-0.7.4",
"lib/sammy/sammy-0.7.4.min",
"lib/toastr/toastr",
"lib/toastr/toastr.min"
],
"exclude": [],
"keepBuildDir": true,
"optimize": "uglify2",
"out": "C:\\DNNDev.me\\DesktopModules\\Framework.App\\App\\main-built.js",
"pragmas": {
"build": true
},
"wrap": true,
"insertRequire": [
"main"
]
}
In your path you are setting your reference to knockout equal to the mapping plugin, which is no bueno.
As shown in this answer, Durandal.js optimizer not working (empty main-built.js) you can run it like Rainer shows and you should see a more specific error.
One thing that I found - if you remove a view model or use a folder or directory as a purgatory (about to be deleted) those files may not be used in your app but if they are in the file structure they will still be evaluated by the optimizer.
EDIT
Check here for more info on the optimizer - Tracking down optimizer issues in durandal.js
Also, are you building debug or release? Are you targeting the correct one? durandal optimizer references wrong path when building it as a post build process in Visual Studio
Also, if you are referencing Knockout.js, I think you mean to reference "lib/knockout/knockout-2.3.0" not the knockout mapping plugin.
Unless I am missing something you shouldn't have to add those paths to your main.js file. Breeze and Knockout should be referenced already. Depending on your project type, your editor, etc... it is probably bundled in your App.Start folder under DurandalBundleConfig. If it is not then are you just referencing the libraries from your index.html?
Move them into the bundle config if that is the case (something like this) -
bundles.Add(
new ScriptBundle("~/scripts/vendor")
.Include("~/Scripts/jquery-{version}.js")
.Include("~/Scripts/jquery-ui-{version}.min.js")
.Include("~/Scripts/knockout-{version}.js")
.Include("~/Scripts/sammy-{version}.js")
.Include("~/Scripts/bootstrap.min.js")
.Include("~/Scripts/knockout-bootstrap.min.js")
.Include("~/Scripts/Q.js")
.Include("~/Scripts/breeze.debug.js")
);
Note that you need to load Q prior to Breeze, as Breeze depends on Q.

RequireJS Optimizer is not combing files

I am using the following build file and when I build (r.js -o jsbuild/build.js) all the files in the 'script' folder are minified into the 'productionScripts' folder but they are not combined into the config.js file. Therefore I'm still getting the multiple http requests for all the dependencies.
Is there something wrong with my config or am I completely missing something about requireJS?
({
appDir : "../assets/scripts",
baseUrl : "",
dir : "../assets/productionScripts",
optimize: "uglify",
paths: {
config: 'assets/scripts/config'
},
modules: [
{
name: "config"
}
],
mainConfigFile : "../assets/scripts/config.js"
})
Of course once I post I figure it out. I was mixing concepts. My config was saying minify the 'assets/scripts' folder and that's what it was doing.
I updated the script to just minify the main file. In this case 'assets/scripts/config.js' and that's when it combines dependencies. See appropriate config below. The key is to not use 'dir', 'appDir', and 'modules', this is specific to minifying the folder. Use 'out' to specify where dependencies will be minified and combined.
({
baseUrl : "../assets/scripts",
optimize: "uglify",
name: 'config',
mainConfigFile : "../assets/scripts/config.js",
out: "../assets/productionScripts/config.js"
})

Resources