Serving Static files on AWS Django application - django

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

Related

Django project is not reading my static css file

I am working on a django project and for some reason the style.css file is not read. However, my static images are working. Not really sure what the issue is, any help is greatly appreciated. There are also no errors showing in the console and terminal..
Link to my github repository
https://github.com/Amanuel763/petwebsite
Add STATIC_URL and STATIC_ROOT to your urls.py. See more about Serving static files during development[Django-doc]
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)

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/'

How to let PIL's Image.open find files from static?

I want to access a file in static from a module called "generate.py" inside my app. However I don't really have any idea how to do it.
I believe I've properly "installed" the app because i can access the .html file in the App
Things I've tried in generate.py
1 -
from django.conf.urls.static import static
Image.Open(static('resources/App/template/photothatiwanttoopen.jpg'))
Error I get from code above: 'list' object has no attribute 'read'
2 -
from django.conf import settings
Image.Open(settings.STATIC_URL+'resources/App/template/photothatiwanttoopen.jpg')
Error I get from code above: [Errno 2] No such file or directory: '/static/resources/App/template/photothatiwanttoopen.jpg'
Here's my folder structure view
- Project
- App
- templates
- App
- app.html
- apps.py
- generate.py <<< Script
- models.py
- urls.py
- views.py
- Project
- settings.py and stuffs
- static
- resources
- App
- template
- photothatiwanttoopen.jpg
- manage.py and stuffs
Here's last few lines of my settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Let me know if you need any more information.
STATIC_URL has no concept of the actual location on the filesystem.
That's where STATIC_ROOT comes into play.
Your optimal choice is likely going to be:
Image.Open(os.path.join(STATIC_ROOT, 'resources/App/template/photothatiwanttoopen.jpg'))
That is assuming of course you've already collected the staticfiles (manage.py collectstatic) and you have imported STATIC_ROOT from django settings.

django static files cannot be found

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

Django Static Files CSS

How can I view my static css files? I've set my STATIC_ROOT, and am using python manage.py runserver.
In my development environment, according the docs, I only need to place my static files (in this case, /static/css/typography.css) in my STATIC_ROOT, and python manage.py runserver will automatic create the views necessary to access it if I have DEBUG = True.
STATIC_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), "static")
I've also tried manually adding the views in URLConf, which won't display the css file either:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()
In my template, the {{ STATIC_URL }} gets to the correct address (/static/css/typography.css), but it will not serve the file when I try to access it:
<link href="{{ STATIC_URL }}css/typography.css" rel="stylesheet" type="text/css">
Notes: The other Django related static files questions on StackOverflow are over two years old. Django version 1.3b1 differentiates STATIC (static files, such as css and images) and MEDIA (user-uploaded file).
Besides. all the tries mentioned above, you must also make sure that your template is receiving the RequestContext when called from the view.
http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/
This link gives various ways of doing the same and you could choose any one. :) Also, the TEMPLATE_CONTEXT_PROCESSORS must be added to settings.py for this to take effect.
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"myapp.processor.foos",
)
Note: STATIC_ROOT is the place where all your static files are stored by Django after collecting them from STATICFILES_DIRS.
Runserver will pick them up from the path mentioned in STATIC_ROOT, so STATIC_URL should point to the same location as STATIC_ROOT.
Answered here: Django staticfiles app help
I was putting my files in STATIC_ROOT, so adding this works:
STATICFILES_DIRS = (STATIC_ROOT,)
In development:
#settings.py have this by default
STATIC_URL = '/static/'
This means when you want to use static files, django will look for them in folder 'static' in your app directory. So you need to create folder 'static' in every your app and put inside your static files.
In production:
1. Make place to hold static files from all app's
STATIC_ROOT = "/var/www/example.com/static/"
2. Run python manage.py collectstatic to collect static files from all app's in STATIC_ROOT folder.
3. In settings.py change DEBUG=False and ALLOWED_HOSTS = ['yourhostadress'].
4. Point your webserver to STATIC_ROOT folder (eg. for Apache2.4):
Alias /static/ /path/to/mysite.com/static/
<Directory /path/to/mysite.com/static>
Require all granted
</Directory>
After this setup, your django project should be able to run (using mod_wsgi) and use static files on Apache web server.