I used cPanel and deployed a Django application on my server using passenger_wsgi.py
. The problem is when I'm trying to access static files (like admin CSS file: static/admin/css/base.css
) I'm facing with 404 error.
I've already done collectstatic
and added PassengerPathInfoFix
method to passenger_wsgi.py
file but the output log is
Not Found: /home/mysite/public_html/build/static/admin/css/base.css
even though the outputted path exists and I can edit it using vim
.
My settings.py
:
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = "/static/"
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Any help would be appreciated.
CodePudding user response:
Add this into url.py
from django.conf.urls.static import static
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Hope this help!
CodePudding user response:
You can try to change STATIC_URL to STATICFILES_DIRS, this work with me!
STATICFILES_DIRS = [
BASE_DIR / 'static',
BASE_DIR / 'static/admin',
]
CodePudding user response:
Thanks to Ali's answer, For anyone with the same problem, here are the steps I've done. Wish it would be helpful:
- Make sure your
settings.py
file contains these lines:
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = "/static/"
run
python manage.py collectstatic
Edit your
passenger_wsgi.py
and add these lines:
# ...
# Import WSGI of your project
# Project Static File Path
cwd = os.getcwd()
sys.path.append(cwd)
sys.path.append(cwd '/myapp')
SCRIPT_NAME = os.getcwd()
class PassengerPathInfoFix(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
from urllib.parse import unquote
environ['SCRIPT_NAME'] = SCRIPT_NAME
request_uri = unquote(environ['REQUEST_URI'])
script_name = unquote(environ.get('SCRIPT_NAME', ''))
offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0
environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0]
return self.app(environ, start_response)
application = PassengerPathInfoFix(application)
- If you deployed your Django project in a subfolder inside
public_html
and not in thepublic_html
directory (as mine), copy thestatic
folder topublic_html
or create symbolic link usingln -s public_html/static/ public_html/subfolder/static/
(The point is thestatic
files only load from your domain/subdomain base directory) (maybe there is a better solution but this solved my problem)
So I moved the project to the base directory of my domain and it worked.