Error transferring django project from windows to linux - linux

My project with py3 and django worked well in win10. But when I tried to make it work in linux, a 404 eror of static file appeared.
The error message is below.
[28/Sep/2017 09:32:57] "GET /static/home/cys/prj/.../cls_demo/static/c73f33679ff4328816dee4450044174e.jpg HTTP/1.1" 404 1955
** Settings.py **
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, "clsapp", "static"),
]
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder"
)
**Sample of how I call static files through my templates**
{% load staticfiles %}
<div class="img" style="background-image: url('{% static img_path %}')">
</div>
There is different code between win10 version and linux version. Why did this error appear? How to fix it...

Related

Error 404 on Browser not showing Static folder file

When i imported os at first and write at the most bottom of settings.py
STATICFILES_DIRS =[
os.path.join(BASE_DIR,
'static')
]
To run my static folder which contains test.txt
But when I tried to run it on Opera it shows Page not foun 404.
Please tell what Can be the issue in this Django program.
You need to run the following command to collect static files first
python manage.py collectstatic
Your settings.py file must include
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'))
After this you import static method in your urls.py file of project and then add
from django.conf.urls.static import static
urlpatterns = [ ]+
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

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.

Static Files are set but not working. I keep getting 500 error

Can someone please look at the way I have my static files set up and tell me if there is something I am missing? Thank you.
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
The solution I found for this error is:
sudo chmod a+w/'projectmain'/'projectfolder'/media/images

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.

TemplateDoesNotExist at /music/1/favourite/ music/details.html

I am new to Django and i am using it's version 2.0.7. I have already created template named as details.html but it's still not showing
The video tutorial which i am referring is https://www.youtube.com/watch?v=qgGIqRFvFFk&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK&index=24
The error which I got is this
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/music/1/favourite/
Django Version: 2.0.7
Python Version: 3.6.6
Installed Applications:
['music.apps.MusicConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed 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']
Template loader postmortem
Django tried loading these templates, in this order:
Using engine django:
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\Desktop\website\music\templates\music\details.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\templates\music\details.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\templates\music\details.html (Source does not exist)
Traceback:
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py" in __getitem__
77. list_ = super().__getitem__(key)
During handling of the above exception ('song'), another exception occurred:
File "C:\Users\Adesh\Desktop\website\music\views.py" in favourite
22. selected_song = album.song_set.get(pk=request.POST['song'])
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py" in __getitem__
79. raise MultiValueDictKeyError(key)
During handling of the above exception ('song'), another exception occurred:
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Adesh\Desktop\website\music\views.py" in favourite
26. 'error_message':"You did not select a valid song",
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\shortcuts.py" in render
36. content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader.py" in render_to_string
61. template = get_template(template_name, using=using)
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader.py" in get_template
19. raise TemplateDoesNotExist(template_name, chain=chain)
Exception Type: TemplateDoesNotExist at /music/1/favourite/
Exception Value: music/details.html
My template is as follows named as details.html
<img src="{{ album.album_logo}}">
<h1>{{ album.album_title }}</h1>
<h2>{{ album.artist }}</h2>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="{% url 'music:favourite' album.id %}" method="post" >
{% csrf_token %}
{% for song in album.song_set.all %}
<input type="radio" id="song{{ forloop.counter }}" name="song"
value="{{ song.id }}">
<label for="song {{ forloop.counter }}">
{{ song.song_title }}
{% if song.is_favourite %}
<img src="random_image.png"/>
{% endif %}
</label><br>
{% endfor %}
<input tye="submit" value="Favourite">
</form>
Check your template folders in the settings, in this part of the error you can see Django can't find the template:
Using engine django:
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\Desktop\website\music\templates\music\details.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\templates\music\details.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\templates\music\details.html (Source does not exist)
These are the directories that Django tried to find the template in. The directories that Django looks for are specified in the settings.py file of your project, either this variable: TEMPLATE_DIRS or TEMPLATES has the paths that Django looks for templates.
Either move the template to one of these folders or add the folder where you've saved the template to this variable.
Also see this part of the Django documentation about templates:
https://docs.djangoproject.com/en/2.0/topics/templates/#django.template.backends.base.Template.render
Try to add the path of your "Template" directory on settings.py file. You can check the code block below; I added full path of my template directory to 'DIRS' in TEMPLATES part and it solved my problem.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [r'C:\Users\Exper\PycharmProjects\Django\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',
],
},
},
]

Resources