Static file 404 not found Django - django

I can't retrieve a static file from my template
I have the my project structure as follow:
.
├── db.sqlite3
├── gr_recommendation
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   ├── urls.pyc
│   ├── wsgi.py
│   └── wsgi.pyc
├── manage.py
└── recom
├── admin.py
├── admin.pyc
├── apps.py
├── __init__.py
├── __init__.pyc
├── migrations
│   └── __init__.py
├── models.py
├── models.pyc
├── static
│   ├── recom
│   │   └── style.css
│   └── style.css
├── templates
│   └── recom
│   └── index.html
├── tests.py
├── urls.py
├── urls.pyc
├── views.py
└── views.pyc
In settings.py I have the basic configuration:
DEBUG = True
INSTALLED_APPS = [
'django_cassandra_engine',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'recom',
]
STATIC_URL = '/static/'
According to the documentation:
Serving the files
In addition to these configuration steps, you’ll also need to actually serve the static files.
During development, if you use django.contrib.staticfiles, this will be done automatically by runserver when DEBUG is set to True (see django.contrib.staticfiles.views.serve()).
My index.html template there is the following code:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'recom/style.css' %}" />
<h1>{{book.title}}</h1>
When I go in the application path /recom the html is showed without the css rules and I have the following error in the server console:
[25/Jan/2016 13:30:59] "GET /static/recom/style.css HTTP/1.1" 404 2126
If a try to access to http://my_server_ip:8000/static/recom/style.css
I have a 404 error.
Can anyone help me to make it works?

Related

Issue with static files when deploying Django app to Heroku

My project folder looks this:
├── Procfile
├── core
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-39.pyc
│   │   └── views.cpython-39.pyc
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── db.sqlite3
├── inspirationSources.txt
├── manage.py
├── package-lock.json
├── package.json
├── react-frontend
│   ├── README.md
│   ├── build
│   │   ├── asset-manifest.json
│   │   ├── favicon.ico
│   │   ├── index.html
│   │   ├── logo192.png
│   │   ├── logo512.png
│   │   ├── manifest.json
│   │   ├── robots.txt
│   │   └── static
│   ├── package-lock.json
│   ├── package.json
│   ├── public
│   │   ├── favicon.ico
│   │   ├── index.html
│   │   ├── logo192.png
│   │   ├── logo512.png
│   │   ├── manifest.json
│   │   └── robots.txt
│   └── src
│   ├── App.css
│   ├── App.js
│   ├── App.test.js
│   ├── assets
│   ├── components
│   ├── hooks
│   ├── index.css
│   └── index.js
├── requirements.txt
├── spotify
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-39.pyc
│   │   ├── admin.cpython-39.pyc
│   │   ├── apps.cpython-39.pyc
│   │   ├── cluster.cpython-39.pyc
│   │   ├── credentials.cpython-39.pyc
│   │   ├── models.cpython-39.pyc
│   │   ├── urls.cpython-39.pyc
│   │   ├── util.cpython-39.pyc
│   │   └── views.cpython-39.pyc
│   ├── admin.py
│   ├── apps.py
│   ├── cluster.py
│   ├── credentials.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── __init__.py
│   │   └── __pycache__
│   ├── models.py
│   ├── templates
│   ├── tests.py
│   ├── urls.py
│   ├── util.py
│   └── views.py
├── spotifycluster
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-39.pyc
│   │   ├── settings.cpython-39.pyc
│   │   ├── urls.cpython-39.pyc
│   │   └── wsgi.cpython-39.pyc
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── tutorialSources.txt
When I deploy with git push heroku main it seems to be fine but when I open the app in browser using the complementary url, I get the following errors on screen (debug mode is on):
TemplateDoesNotExist at /
build/index.html
Request Method: GET
Request URL: https://nameless-taiga-02413.herokuapp.com/
Django Version: 3.1.7
Exception Type: TemplateDoesNotExist
Exception Value:
build/index.html
Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/template/loader.py, line 19, in get_template
Python Executable: /app/.heroku/python/bin/python
Python Version: 3.9.4
Python Path:
['/app/.heroku/python/bin',
'/app',
'/app/.heroku/python/lib/python39.zip',
'/app/.heroku/python/lib/python3.9',
'/app/.heroku/python/lib/python3.9/lib-dynload',
'/app/.heroku/python/lib/python3.9/site-packages']
Server time: Fri, 30 Apr 2021 10:08:26 +0000
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.filesystem.Loader: /app/react-frontend/build/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/templates/build/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/templates/build/index.html (Source does not exist)
I have the following settings in my settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
Also I have whitenoise in my middleware list
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
...]
The templates section in settings.py looks as follows
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'react-frontend')],
'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 expected that Heroku would be able to find the static folder based on the STATIC_DIRS variable but that doesn't seem to be the case. Any clue what's going on here?
So actually it was a really stupid mistake. react-frontend was a broken submodule and I needed to fix that by making sure .git/config didn't have submodules and removing react-frontend from the cache (No submodule mapping found in .gitmodules for path and missing .gitmodules file). Commit and pushed again and it worked...
if your DEBUG is set to False Django din't handle STATIC FILES. Heroku provide some configuration to serve STATIC FILES
STEP-1 : install whitenoise
$ pip install whitenoise
STEP-2 : check in settings.py whitenoise middleware by default it available in MIDDLEWARE if it's not that add it.
MIDDLEWARE = (
'whitenoise.middleware.WhiteNoiseMiddleware',
...)
STEP-3: add this in your settings.py
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

`FileNotFoundError`: when issue `python manage.py collectstatic`

When I tried to issue commands to collect staticfiles
In [41]: ! python manage.py collectstatic
It throw FileNotFoundError:
FileNotFoundError: [Errno 2] No such file or directory:
'/Users/me/Desktop/Django/forum/static'
Nevertheless, there exist file '/Users/me/Desktop/Django/forum/static'
In [44]: ! tree -L 2
.
├── db.sqlite3
├── forum
│   ├── __init__.py
│   ├── __pycache__
│   ├── settings.py
│   ├── static
│   ├── templates
│   ├── urls.py
│   └── wsgi.py
├── forums
│   ├── __init__.py
│   ├── __pycache__
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   ├── models.py
│   ├── static
│   ├── templates
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── ll_forum
│   ├── bin
│   ├── include
│   ├── lib
│   ├── pip-selfcheck.json
│   ├── pyvenv.cfg
│   └── share
└── manage.py
14 directories, 15 files
The setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#my apps
"forums"
]
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"), #notice the comma
)
You should provide the STATIC_ROOT in your settings, by default Django looks for a directory named static in your root project, so that 's why your get this /Users/me/Desktop/Django/forum/static'``FileNotFoundError the folder is not present.
You have that directory static next to your settings, it should not be there. By the way also your templates should not be there.
Move them back to your root project
├── db.sqlite3
├── forum
│ ├── __init__.py
│ ├── __pycache__
│ ├── settings.py
| |---static # remove this
│ ├── templates # remove this here
│ ├── urls.py
│ └── wsgi.py
|---static -- # GOOD
|---templates # GOOD
You need to have static directory outside from Django App. This directory and your Django app should be separate.
Then, if you specify :
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"), #notice the comma
)
It means your static directory is in your base directory. Or you have only forum, forums, ll_forum ...
If you want absolutly keep your static directory in your Django App, make this directory in the BASE_DIR (move from initial position to your base project) and write something like this in settings.py file :
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),]
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static/')
Finally, you should have something like this :
.
├── db.sqlite3
├── forum
│ ├── __init__.py
│ ├── __pycache__
│ ├── settings.py
│ ├── static
│ ├── templates
│ ├── urls.py
│ └── wsgi.py
├── forums
│ ├── __init__.py
│ ├── __pycache__
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── ll_forum
│ ├── bin
│ ├── include
│ ├── lib
│ ├── pip-selfcheck.json
│ ├── pyvenv.cfg
│ └── share
└── manage.py
│
└── static
│
└── templates

Create react app + Django deployment Uncaught SyntaxError: Unexpected token <

I've been trying to deploy an app to pythonanywhere but the page is just blank, because main.6f259c1b.js file throws error`
Uncaught SyntaxError: Unexpected token <
`
I've been following the instuctions on this article https://www.fusionbox.com/blog/detail/create-react-app-and-django/624/ and this https://www.techiediaries.com/create-react-app-django/
both articles suggest to create a view with following content
class FrontendAppView(View):
"""
Serves the compiled frontend entry point (only works if you have run `yarn
run build`).
"""
def get(self, request):
try:
with open(os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')) as f:
return HttpResponse(f.read())
except FileNotFoundError:
logging.exception('Production build of app not found')
return HttpResponse(
"""
This URL is only used when you have built the production
version of the app. Visit http://localhost:3000/ instead, or
run `yarn run build` to test the production version.
""",
status=501,
)
and in app website/urls.py
urlpatterns = [
url(r'^', FrontendAppView.as_view())
]
Those instructions don't work for me. It's something that related to pushState routing, react-routing, I don't know. My app works ok in development server in localhost:3000, it only seen in pythonanywhere and local apache server with mod_wsgi.
This is my config of local apache(from Django documentation):
WSGIScriptAlias / /home/user/projects/myproject/myproject/wsgi.py
WSGIPythonHome /home/user/.virtualenvs/myproject
WSGIPythonPath home/user/projects/myproject/
<Directory /home/user/projects/myproject/myproject>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
This is root
DocumentRoot "/srv/http"
Part of my settings
REACT_APP_DIR = os.path.join(BASE_DIR, 'frontend')
STATIC_URL = '/static/'
STATIC_ROOT = 'static'
STATICFILES_DIRS = [
os.path.join(REACT_APP_DIR, 'build', 'static')
]
All software are latest release.
Maybe this comment solves my problem, I just don't understand it. https://github.com/facebookincubator/create-react-app/issues/1812#issuecomment-286511320
This is my localhost screenshot
My project directory structure
├── api_v0
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── __pycache__
│   ├── serializers.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── myproject
│   ├── __init__.py
│   ├── local.py
│   ├── __pycache__
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── frontend
│   ├── build
│   ├── node_modules
│   ├── package.json
│   ├── package-lock.json
│   ├── public
│   ├── README.md
│   └── src
├── manage.py
├── requirements.txt
├── static
│   ├── admin
│   ├── css
│   ├── js
│   ├── media
│   └── rest_framework
└── website
├── admin.py
├── apps.py
├── __init__.py
├── management
├── middleware.py
├── migrations
├── models.py
├── __pycache__
├── tests.py
├── urls.py
└── views.py
Review the styles referenced on the page and make sure that all the CSS files are referenced on the page using a <link> tag and not a <script> tag.
reference
also there are nginx adubting , you can do it for request your site adminstator help

What am I missing in Django production deployment?

I have the following codes for deploying a Django 1.9 project named deploy_project on a CentOS 7 server.
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "deploy_project.settings")
application = get_wsgi_application()
The above was generated by default.
httpd.conf
WSGIScriptAlias / /var/www/deploy_project/deploy_project/wsgi.py
WSGIPythonPath /var/www/deploy_project
<Directory /var/www/deploy_project/deploy_project>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
My project directory is in /var/www/deploy_project. Inside that I have an app called Deploy, the project settings folder called the same as the project name deploy_project and the manage.py file. I also have a db.sqlite3 file as I am not using MySQL, but my app just runs a view which shows Hello World. I am not using the database.
When I visit the server IP from browser, I receive a 404 Not Found page with the message The requested URL / was not found on this server..
tree output of project folder
├── db.sqlite3
├── deploy
│   ├── admin.py
│   ├── admin.pyc
│   ├── apps.py
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __init__.pyc
│   ├── models.py
│   ├── models.pyc
│   ├── templates
│   │   ├── 404.html
│   │   └── deploy
│   │   └── hello.html
│   ├── tests.py
│   ├── urls.py
│   ├── urls.pyc
│   ├── views.py
│   └── views.pyc
├── deploy_project
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   ├── urls.pyc
│   ├── wsgi.py
│   └── wsgi.pyc
└── manage.py
project urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('deploy.urls')),
]
app urls.py
urlpatterns = [
url(r'^$', views.Hello, name='hello'),
]
views.py
def Hello(request):
return render(request, "deploy/hello.html", {})
hello.html
Hello World!
Being the dumb developer that I am, I didn't restart apache service, so my settings didn't take effect.
For CentOS 7 my command was:
sudo systemctl restart httpd
That solved my problem. Thanks for your time #BurhanKhalid.

django serving static css files

I am relatively new to Django development.I have a css file inside a /static/css directory.
When I try to run the url no CSS is applied to my template. the python manage.py runserver window shows following error
[01/Jan/2013 20:00:40] "GET /home/prat/PROJECT_ROOT/SOURCE_ROOT/static/css/Style.css HTTP/1.1" 404 2207
Can someone please point me how to debug this. I have read multiple stackoverflow questions and added the following setting in my settings.py.
PROJECT_R = os.path.abspath(os.path.dirname(__name__))
PROJEECT_R = PROJECT_R + "../"
STATIC_ROOT = os.path.join(PROJECT_R, "static")
STATIC_URL = 'static/'
.
├── manage.py
├── README
├── SOURCE_ROOT
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   ├── urls.pyc
│   ├── wsgi.py
│   └── wsgi.pyc
├── static
│   ├── css
│   │   ├── README
│   │   └── Style.css
│   ├── images
│   │   └── README
│   └── js
│   └── README
├── template
│   ├── base.html
Here's how I usually go about managing dynamic project root:
from os.path import dirname, realpath, join
PROJECT_ROOT = dirname(realpath(__file__))
And then further below, the static root:
STATIC_ROOT = join(PROJECT_ROOT, 'static/')
And then you reference static files like so:
{{ STATIC_URL }}css/Style.css
EDIT:
See the documentation for more information.