django static files cannot be found - django

In my settings file i have the following
STATIC_URL = '/static/'
my app name is reg_service
So my directory structure is like reg_service/reg_service/settings.py
And i have the static directory in reg_service/static/js
reg_service/manage.py
reg_service/reg_service
reg_service/templates
But in my template if i include the following script the result is "GET /static/js/jquery.min.js HTTP/1.1" 404 1652 whats is wrong here
<script src="{{ STATIC_URL }}js/jquery.min.js"></script>

The idea of django is that you should serve your static files directly through your web server.
For development purposes you can 'trick' django to serve the static files themself:
urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Django will find your static files, and serve them under the url defined under STATIC_URL.
That's not very performant nor secure, but works ok for development. For production you should configure your web server (Apache, Nginx, whatever) to serve the files directly under the url defined in STATIC_URL.
For more information see: https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-during-development

Related

Why doesn't Django serve static files when the dubug=False in settings?

when I tried to run the project, static files are missing, and the settings.debug is set to False.
Django does not serve static files in production (when DEBUG = False) because doing so would be in their own words (As stated in the section Serving static files during development of the documentation):
This method is grossly inefficient and probably insecure, so
it is unsuitable for production.
Why is this inefficient one might say? Well static files are mostly larger in size than your normal HTML files, plus a website is bound to have lots of static files. If Django served static content even in production much of the time of the server would be wasted in serving these static files. Plus to serve multiple requests at the same time we run multiple Django processes simultaneously, if there are many requests for static files this will cause the processes to waste time serving them, causing other requests to wait if there are no free processes.
Plus as #Reda Bourial mentions in their comment Django doesn't handle compression well (One would want to compress their static files so that less bandwidth is required, both by the server and the client). Furthermore Django should focus more on the task it is designed for, which is rendering the pages requested by users (A CPU bound task), whereas serving static files is mostly just an Input / Output (I/O) task and for Django to spend time on these tasks (even when it is not efficient at them) is clearly a waste.
Servers like NGINX or Apache can serve static files much more efficiently, hence it is best to use them in production instead of having Django do it. For details on how to configure static files for production see Deploying static files [Django docs]
Actually in Django, while you run your project on the development server it won't serve your static files when you try to serve the static files after changing DEBUG settings to False. It will work properly on the production or stagging server but not on localhost server.
Still, there is a way to do this you can get by running your development server on insecure mode.
Try this,
python manage.py runserver --insecure
it is not recommended, but if you are just getting started and want to understand more about what's going on, then you can also link directly:
urls.py:
from django.conf.urls.static import static
from django.contrib import admin
from djangoapp import settings
from webtools.views import *
from django.urls import path, include
"""
direct link on the server in production
"""
from django.views.static import serve as mediaserve
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('webtools.urls')),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
path('__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
else:
# direct link on server in production
urlpatterns += [
url(f'^{settings.MEDIA_URL.lstrip("/")}(?P<path>.*)$', mediaserve, {'document_root': settings.MEDIA_ROOT}),
url(f'^{settings.STATIC_URL.lstrip("/")}(?P<path>.*)$', mediaserve, {'document_root': settings.STATIC_ROOT}),
]
settings.py:
DEBUG = False
.
.
.
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = []
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Serving Static files on AWS Django application

I know that this isn't the first time the question has been asked, so I'm apologizing up front. I've been working on this for a few days and still have no clue how to proceed.
I followed this tutorial to the tee: https://aws.amazon.com/getting-started/hands-on/deploy-python-application/
The website is up and running, but of course the static files won't load.
Here's where I'm at. In settings.py, I've set my STATIC_ROOT and STATIC_URL to the following:
STATIC_ROOT = os.path.join(BASE_DIR, 'mysite', 'static')
STATIC_URL = '/static/'
I ran collectstatic and gathered all my static files into the mysite app directory. It looks like this:
-mysite
- mysite (app)
- static
- base
- base.css
- settings.py
- urls.py
- wsgi.py
Unfortunately, the static files still fail to load on the website.
Here are my questions:
Suppose I wanted to view the base.css text file on the web. Would I go to www.mysite.com/static/base/base.css? If no, what would the URL be? If yes, why is it not appearing given the current set up?
Per the AWS tutorial, I ran edited the httpd-app.conf file to include the following
Alias /mysite/static /opt/bitnami/apps/django/lib/python3.7/site-packages/Django-2.2.9-py3.7.egg/django/contrib/admin/static
What was the purpose of the edit? How does it impact how the static files are served on the site?
Any help you guys can offer on loading these static files will be a lifesaver.
Your urls.py file needs to be configured to serve your STATIC_URL
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
More on serving static files with Django

How do I get Django to load my favicon from my React build directory?

I am using Django and React to create a web application. When it comes to my React Development server, my favicon.ico loads like it should, but when I build my files, my Django development server doesn't find and render my favicon, and I have no idea why. I've tried renaming my favicon and changing the file type to .png. When I put my favicon into my static directory, and change the file name from favicon to some thing like "icon.ico", then it loads properly. But, I can't have my favicon in my static directory because CRA won't copy it into that directory when it builds. It's probably something small and simple so I'll show y'all all of the related files. Thanks for any insight!
EDIT: I tried collectstatic , but that did not help
EDIT 2: using {% load static %} but this doesn't work because my favicon is in the same directory as my html file. I should also clarify that import links to the parent directory that holds both my html file and my favicon file don't register for some reason.
The import in my build/index.html: <link rel="shortcut icon" type="image/x-icon" href="./favicon.ico"/>
urls.py
from django.contrib import admin
from django.urls import include, path, re_path
from django.conf.urls import include, url
from backend import views
from django.views.generic.base import RedirectView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('backend.urls')),
path(r'^api/<int:pk>$', include('backend.urls')),
path(r'^api/<int:pk>$/', include('backend.urls')),
url(r'^.*$', views.index),
]
my settings.py static settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(FRONTEND, 'build/static/'),
]
CORS_ORIGIN_WHITELIST = (
'http://localhost:3000',
)
Also, let me know if the problem could be in another file
The problem is that the django url routing has no access to the favicon.ico since CRA puts it in /build and all your static files are served from /build/static.
Assuming you haven't ejected, a hacky solution is to copy the favicon.ico into the static folder in your build step in package.json scripts section:
"build": "react-scripts build && cp build/favicon.ico build/static/favicon.ico"
and then in the html template in /public, set the favicon.ico url to
<link rel="shortcut icon" href="/static/favicon.ico">
instead of %PUBLIC_URL%/favicon.ico.
If you have ejected the CRA, you can update your webpack config to move the favicon.ico directly into /build/static

Static Files With Django 1.6

I have spent all day and nothing works. I have seen at least 20 posts here about the same topic and they are different with different suggestions and nothing works for me.
Running Django 1.6 with Python 2.7.+
I'm trying to load the css for the polls app from the django tutorial.
project layout
Project
|-polls
|-static
|-polls
style.css
|static
here is the settings.py
STATIC_URL = '/static/'
STATIC_ROOT = '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/static'
template code
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">
urls.py
urlpatterns = patterns(...)+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
polls/urls.py
urlpatterns = patterns(....,url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/'}),)
After running: python manage.py collectstatic, everything is collected and static folder which is on root gets populated accordingly with the admin and polls folders and files.
I start the server: python manage.py runserver everything works fine except the css is not loaded
this is what i get from the Chrome console when i inspect the html
....
<link rel="stylesheet" type="text/css" href="/static/polls/style.css">
....
which looks fine but gives the following output
[16/Nov/2013 00:44:41] "GET / HTTP/1.1" 404 2141
[16/Nov/2013 00:44:45] "GET /polls/ HTTP/1.1" 200 820
[16/Nov/2013 00:44:45] "GET /static/polls/style.css HTTP/1.1" 404 1649
Any help would be appreciated. I followed everything step by step. I don't know what to do anymore
UPDATE
DEBUG=True
full urls.py
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from PoolsDjangoProject import settings
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'PoolsDjangoProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^polls/', include('polls.urls', namespace='polls')),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
full polls/urls.py
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(),name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote', name='votes'),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/'}),
)
And when i try to access
http://127.0.0.1:8000/static/polls/style.css
I get
Page not found (404)
'polls/style.css' could not be found
I found it necessary to restart the running server after following the steps in
https://docs.djangoproject.com/en/1.6/intro/tutorial06/#customize-your-app-s-look-and-feel
in order to pick up the newly created static directory. That step isn't listed in the tutorial. I have opened a ticket requesting its addition.
I realise this answer is not likely to help your specific case but this question comes up prominently in Google when searching for problems with adding a static directory to the example Polls app.
I ran into this problem too. My problem was that I didn't have my main app in the installed apps, whatever folder that has wsgi.py in it, that needs to be in INSTALLED_APPS.
I struggled with this problem as well.
Here's how I solved it (DEBUG=True):
After creating a project and several apps, I created a directory called "static" that sat alongside my app directories (same level as .manage.py).
I set my static URL to '/static/' in settings
I set my static root to STATIC_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../static/').replace('\\','/')) (BASE_DIR = os.path.dirname(os.path.dirname(__file__)))
I set my staticfiles dirs to STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), '/Users/username/sites/containing_dir/project_dir/static/',) (assumes OSX path)
I added + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to my urls.py for my project
My static media is now served from http://127.0.0.1:8000/static/css/styles.css (assuming runserver command).
Comment if you need addition description!
Firstly it has to be known that Django is not responsible for serving static files on production servers. However, it does serve them when DEBUG=True during development for the sake of debugging.
For serving static files when debug=true you have to do nothing. I don't know why it is creating confusion among newbies on how to setup it. The below should help you create static files for both production and dev modes clearly
Development mode : when DEBUG=True
create your project django-admin.py startproject mysite
create your app manage.py createapp myapp
Add myapp to INSTALLED_APPS in settings.py
In myapp dir, create a folder static
In the myapp/static dir, save a file myfile.css
In settings.py, provide a valid address to STATIC_ROOT folder to store static files. It could be something like os.path.join(os.path.abspath(os.path.dirname(__file__)), "mystatic") if you want to store your collected files at mysite/mysite/mystatic.
run manage.py collectstatic; now you have to see the static file collected at the directory you mentioned above..It should also create one if its not present. You are free to put any directory.
test the url http://127.0.0.1:8000/static/myfile.css
In case if its not working yet, try restarting the site.. New files are not recognized dynamically!

django and static css plus js files

i did a small app on django and it is using templates. Each tempalate use static files such as css, js and images. all those files in same directory as template.
template
main.html
support.html
about.html
...
css
reset.css
style.css
...
img
js
jquery.js
main.js
...
if there is was to configure django development server to load those files without editing html templates files?
i am receiving
http://127.0.0.1:8000/face/css/960_24_col.css 404 NOT FOUND 127.0.0.1:8000
this changes in settings.py didnt help me
STATIC_ROOT = 'C:/Projects/site/website/face/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = ('C:/Projects/site/website/face/static',)
You might want to use the contrib app staticfiles. At the bottom of the doc page you'll see how to use it on development server.
STATIC_URL has been defined as '/static/' so all static files will be served from /static.
In other words /face/css/960_24_col.css is incorrect.
This should be /static/face/css/960_24_col.css , assuming the face directory is located at C:/Projects/site/website/face/static/face.
Might I also advise you not to use absolute paths in your settings file. To find out the absolute path of the root of your project use something like:
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
Here is how I serve static files via the Django dev server.
Defined in urls.py:
from os import getcwd, path as ospath
...
urlpatterns += patterns('',
(r'css/([a-zA-Z0-9_.]+.css)$', 'django.views.static.serve', {'document_root': ospath.join(getcwd(), 'css')}),
(r'images/(.*)$', 'django.views.static.serve', {'document_root': ospath.join(getcwd(), 'images')}),
(r'js/([a-zA-Z0-9_.]+.js)$', 'django.views.static.serve', {'document_root': ospath.join(getcwd(), 'js')})
)