Django Media images not loading when debug=False [duplicate] - python

I've tried different solutions already posted by users, but they didn't work for me.
settings.py of Project
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = False
ALLOWED_HOSTS = ["*"]
STATIC_URL = '/static/'
STATICFILES_DIRS=[
os.path.join(BASE_DIR,'static')
]
STATIC_ROOT=os.path.join(BASE_DIR,'assets')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
All my CSS files are in style folder inside the static folder.
And all images are in the media folder.
Browser Consol Logs
Refused to apply style from 'http://127.0.0.1:8000/static/styles/LandingPage_CSS.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
icons8-user-48.png:1
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Doorakart%20icon.png:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error)
apple.jpg:1
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
banana.jpg:1
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
watermelon.jpg:1
.
.
.
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Refused to apply style from 'http://127.0.0.1:8000/static/styles/LandingPage_CSS.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Example of HTML file
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title></title>
<link rel="stylesheet" href="{% static 'styles/LandingPage_CSS.css' %}">
</head>
...
# IMAGES ARE LOADED LIKE THIS
<img src="media/{{item.itemImage}}" alt="img" class=" card-img-top">
...
Also, I want to disable DEBUG because I want to make my custom 404 Error page.
404 page will also contain static Image and CSS, is it possible? Please help me with that too.

This is expected behavior. Django does not serve static files or media files in production. You should configure nginx, etc. to serve files.
As is specified in the Static file development view section of the documentation:
This view will only work if DEBUG is True.
That’s because this view is grossly inefficient and probably
insecure. This is only intended for local development, and should
never be used in production.
Normally you should configure nginx, apache web server to serve static files. These web servers are likely more efficient, and have more dedicated tooling for security.
Django offers some tooling to help you set up static files, for example with the collectstatic command [Django-doc] to collect static files in a single location. The documentation furthermore describes how to make a basic configuration for apache and nginx.
There is also a package whitenoise if you really want to let Django serve static files in production, but as said in the documentation:
Isn’t serving static files from Python horribly inefficient?
The short answer to this is that if you care about performance and
efficiency then you should be using WhiteNoise behind a CDN like
CloudFront. If you’re doing that then, because of the caching headers
WhiteNoise sends, the vast majority of static requests will be served
directly by the CDN without touching your application, so it really
doesn’t make much difference how efficient WhiteNoise is.
That said, WhiteNoise is pretty efficient. Because it only has to
serve a fixed set of files it does all the work of finding files and
determining the correct headers upfront on initialization. Requests
can then be served with little more than a dictionary lookup to find
the appropriate response. Also, when used with gunicorn (and most
other WSGI servers) the actual business of pushing the file down the
network interface is handled by the kernel’s very efficient sendfile
syscall, not by Python.

I had the same issue and you should update your nginx or any another serve configuration. Just add your media and static path like below.
location /media/ {
root /path/to/your/project;
}
location /static/ {
root /path/to/your/project;
}
Project path means where your media and static directories are located. Wish this helps you.

Related

Vue.js + vue.router + history mode + Django = Error

When I'm using publicPath: '/static/' in my webpack config, my Vue.js app runs fine on a Django Webserver (both dev and production).
However now I'm trying to use history mode. I have to change the publicPath to "/", otherwise the URL always gets a "/static/" in between the domain and actual target.
The Vue.js dev server still runs fine, however both production and development Django server give me these errors in the browser console:
Uncaught SyntaxError: Unexpected token < Resource interpreted as
Stylesheet but transferred with MIME type text/html:
"http://127.0.0.1:8000/6.01a214ce.css".
I've tried several different solutions like:
publicPath: './'
assetsPublicPath: '/static/'
inside base html (gave me an error on compilation)
How can I resolve this issue?
it was actually a framework issue.. im using Quasar..
For some reason you have to change
base: process.env.VUE_ROUTER_BASE,
to
base: "/",
in router/index.js as the default seems to take the static url when you are using Django..
maybe it helps somebody

New added static file not found

added a new static file to my project by copy/paste into the static directory for my project. But I get 'File not found' when checking debug mode in the browser.
This is my folder structure:
- static
- projectname
-OldScript.js
-NewAwesomeScript.js
And this is my base.html
<script src="{% static 'projectname/OldScript.js' %}" type="text/javascript"></script>
<script src="{% static 'projectname/NewAwesomeScript.js' %}" type="text/javascript"></script>
This is the staticfiles_dir in settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
The oldscript.js have been in the project for a long time. Just wanted to add a new static file I need to load in base.html. So after copying the file to my folder I copy the include script code and changed the name to NewAwesomeScript.js.
It's not working and when checking debug in the browser, it says 'File not found 404'.
OldScript.j is loading, NewAwesomeScript.js is not loading.
Copy from Header for the old file that works:
Request URL:http://localhost:8000/static/projectname/OldScript.js
Request Method:GET
Status Code:200 OK (from disk cache)
Remote Address:127.0.0.1:8000
Referrer Policy:no-referrer-when-downgrade
And the Header for the new file:
Request URL:http://localhost:8000/static/projectname/NewAwesomeScript.js
Request Method:GET
Status Code:404 Not Found
Remote Address:127.0.0.1:8000
Referrer Policy:no-referrer-when-downgrade
Tried forcing refresh (ctrl + shift + F5)
I have restarted the server instance. It's in development. So not a production. Therefore I do not need to run 'collectstatic'. But desperate as I am, I also did this.
I have also checked read/write privileges.
Trying to find anything in the documentation about adding new static files. Without luck to finding my mistake.
What have I forgotten to do?

Django uwsgi using css file http1.1 404

I just put my Django application online using uwsgi. I can access it from any computer it working well.. the only thing is uwsgi can't load the css file stored in the /static/myapp/style.css path and I don't why.
The message I get when accessing a page on my site in the uwsgi console is :
GET /static/myapp/style.css => generated 98 bytes in 1msecs (HTTP/1.1 404) 3 header in 100bytes
But the file is actually in /static/myapp/style.css I can see it and it was working well in developpement, but now the website is in production it's not working anymore.
I added these to my settings.py but nothing changed :
STATIC_URL = '/static/' #Was enough in developpement
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = ("/home/user/Django/mysite/static"),
I also tried to add option in my uwsgi command like
--check-static /home/user/Django/mysite/static
Still not working...
I'm quite new to putting online a Django app so maybe it's not supposed to work like that.
My css file is on the same machine as my Django project.
I'm using django 1.11 and uwsgi 2.5.15.
I also tried to used nginx but I couldn't get it work properly and as I just want to access my app online I concluded that uwsgi alone is enough ( Am I wrong ? )
So if you have any idea that would be great !
Best regards
Gozu09

Issues with 'django.contrib.staticfiles',

I have a website that works fine on my 'production server' with the url being something akin to:
https://mymain.site.com
I have had my sys admins build a site out for development and that url is:
https://mymain.site.com/development
It is a different IP address, but I believe the URL is wrecking havoc on django routing. Mostly I notice it in the static section of it.
If I goto the development server settings and change the static url to:
/development/static/
instead of /static/ like it was on production
None of my static files are found. Since the development server is a VM copy the root on the server for static files is the same. So if I run with the /development/static as the dev url it fails to load resources. If I run on my development server with the url being /static/ I am 90% sure it is grabbing the static files from the production server (at a different ip/url). Not totally sure what the fix is here? I am loking for any kind of ideas.
I suspect if the url of my development server was something more akin to:
https://mymain.site.for.development/
then this would work right out of the box from the code copied from the VM just repointing a few things.
So what am I missing to get this to work with the right static files?
I use a CDN for my static file hosting and this is how I have my settings.py file setup:
STATIC_HOST = 'https://cdn.host.com' if not DEBUG else ''
STATIC_URL = STATIC_HOST + '/static/'
When I'm developing I'll set DEBUG = True and everything works as expected. I would imagine you would have to do something like this:
STATIC_HOST = 'https://mymain.site.com' if not DEBUG else 'https://mymain.site.com/development'
STATIC_URL = STATIC_HOST + '/static/'
See if something like that would work.

flask templates works in local env but return error 404 under nginx

I 've read answer [https://stackoverflow.com/a/20895594/305883] but did not help for me.
I have a flask app that can serve a template in localhost or debug at endpoint /path/<int:id>/, but in production with nginx it will fail with error 404.
Flask project has default structure:
app.py
index.html
/templates/mytemplate.html
/static/..
mytemplate.html will load resources from /static/ folder, with jinja syntax.
EDITED
Goal: I want the application to serve:
root / will serve index.html
/path/ will open 'myTemplate.html' and populate it with variables
(jinja); if possible I want static assets included in template (e.g
js, css, images) to be served by nginx;
/api/ will serve api rest.
In my local environment I am using flask server, not ningx, and three end-points are working as expected.
In production, I use flask and ningx.
Root and /api/ edges work; /path/ , used for templating in flask, does not and return error 404.
For setting up nginx I followed the steps in this tutorial:
[https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-14-04]
The template in flask is served by:
#application.route('/path/<int:id>/')
def graph_template(id):
meta = {'og:image':'/url/image.jpg'}
try:
key = decode(id)[0]
except:
# todo replace with error 400
return jsonify({'error':'Something got wrong. ID not found'})
return render_template('mytemplate.html', meta=meta, id = id)
I am having difficulties in debugging and find the problem, making /path/ display the template.
nginx configuration
server {
listen 80;
# is this block to serve index on root only ?
# or will search for index files also in routes /path/ in ningx and/or flask?
root /var/www/mySite;
index index.html index.htm;
location /api {
# try_files $uri $uri/ /index.html;
include uwsgi_params;
uwsgi_pass unix:/var/www/mySite/myApp.sock;
# auth_basic "API Login";
# auth_basic_user_file /etc/nginx/pw_file;
# allow 127.0.0.1;
# allow XX.XX.XXX.XXX;
# deny all;
}
location /static {
alias /var/www/mySite/static;
}
}
I tried the following:
Included a proxy_pass:
location / {
proxy_pass http://127.0.0.1:8080;
}
result: cause error 502
Tried by changing port to :80
location / {
proxy_pass http://127.0.0.1:80;
}
result: error 404
Tried with uwsgi_pass socket at /path/ endpoint
location /path/ {
include uwsgi_params;
uwsgi_pass unix:/var/www/mySite/myApp.sock;
}
Result: This route does not exist http://example.com/path/
Which I don't understand because flask should serve the template here - at least not a misconfiguration error 502.
Answer at: [Python Flask server crashing on GET request to specific endpoint: shown two sockets for each endpoint - do I need to use such setup?
I m trying to document myself on what a socket is and using nginx documentation but sorry I m not that competent in it and I m moving a bit in darkness.
Could you help in debugging the problem?
YAII! I was able to find the answer myself:
adding this block in nginx worked out for serving templates from flask with nginx:
location /path/ {
include uwsgi_params;
uwsgi_pass unix:/var/www/mySite/myApp.sock;
}
where /path/ is the endpoint of the template.
I was receiving the message above because flask was actually handling the 404 error, due to I wrote my decorator to hit /path/<int:id> and handling 404 requests with:
#application.errorhandler(404)
def page_not_found(error):
return 'This route does not exist {}'.format(request.url), 404
However, I will be very grateful if someone could add some comments explaining how the routing between flask and nginx actually works, and a distinction between using a uwsgi_pass and proxy_pass (which I found in different tutorials), and the use of sockets (tutorial I followed).
As example, in this question [Python Flask server crashing on GET request to specific endpoint: the user use two sockets for each endpoint, and for me as beginner I thought it may have been the issue and it is not.
With this configuration, I understood flask will handle the .html template: does it handle also the resource in the template (js, css) or are they served by nginx (please see configuration above, all assets are in /static/ folder)
Would there be a better configuration to exploit ningx capabilities in serving flask templates ?
Comments most appreciated!
I assume your local env works without nginx, right? So, lets have a look:
In local environment, hitting /path/ (with no id) will return an error of url not found, which is ok. Instead in prod environment, nginx will search for /path/index.html - although I have not mentioned in flask decorator.
Have a look at line three of your nginx config. In there, you specified that nginx should look for index.html.
In local env, if I hit /path/id/ it works ok. In production env, it returns error 404, no such file or directory.
I assume, this is because you don't pass any traffic to your flask app. You need something along the lines of:
location / {
proxy_pass http://127.0.0.1:8080; #Change to match your environment
}
You're missing these (if not, please show your whole nginx config), so nginx will search for static files on your storage. However, these requests can't be served by static files, but instead your backend (aka your flask app) has to render and create these dynamically. For this to work, you have to send the traffic there.
I have not found an error due to failing with resources from /static/ folder (e.g. in permission); it looks like flask cannot load or be allowed to serve the templates.
Template file can be loaded by the browser at /mysite/templates/mytemplate.html Static folder permission is set on 403, but /static/js/file.js will be read.
Sorry, I don't get this. Could you elaborate?

Categories

Resources