简体   繁体   中英

Django: Why are my static files not showing up and always giving me a 404 error when DEBUG=False?

I am working on my Windows Machine, trying to develop multiple apps for a project called "portal". After working on it, I have set DEBUG=False, and now all my static files are giving me a 404 error after loading any page. When running python manage.py runserver in CMD, I get this when loading a page:

[02/Dec/2018 14:10:14] "GET /account/sign-in HTTP/1.1" 200 6249
[02/Dec/2018 14:10:14] "GET /static/fonts/fonts.css HTTP/1.1" 404 96
[02/Dec/2018 14:10:14] "GET /static/css/argon.css HTTP/1.1" 404 94
[02/Dec/2018 14:10:14] "GET /static/branding/logo.png HTTP/1.1" 404 98

I have looked at over 20+ posts about this which were mostly the same and I have followed all of their steps, such as:

  • I have set these in my settings.py file: STATIC_URL = '/static/' , STATICFILES_DIRS = ['portal/static/'] (I have a static folder in the folder that holds files like settings.py), and STATIC_ROOT = os.path.join(BASE_DIR, "static")
  • I have called python manage.py collectstatic

I have even created a new Django test project and did all these steps above, and they ARE working for that new test project. I have even removed all files in __pycache__ and reset my migrations, and database files.

Are there any other possible secure (I have seen others use cheats such as --insecure) solutions to fix my project so it can go into production other than the other solutions above?

So I looked more into what Jon Clements and the others said about how Django won't handle static files anymore when DEBUG=False , and that you need an HTTP Web Server to serve those files. That's actually true . I never thought that before because my other projects had their static files still served, but it could have been because my browser cached those files.

Here's another post which proves this:
Why does DEBUG=False setting make my django Static Files Access fail?

Here's a solution to serve static files based off where your hosting your code:

Learn more about Django static files deployment (official documentation) here: Deploying static files

Just to add something @Alvin Tang, For the purpose of testing your project in production when DEBUG = False you may run the server using: python manage.py runserver --insecure . This assumes a False Debug settings, imitates a production environment and deploys your project serving your static files just as expected (or at least this is what I think it does) provided your static settings are correct - which is true in most cases. Tested and working on Django == 3.0.6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM