I've got some static files that are currently serving from Amazon S3. This obviously isn't effective because I can't collectstatic every time I make a minor change. Whenever I'm developing I want to serve from my project where the static files are collected from. The project structure looks partially like this:
myproject
-app
--templates
-myproject
--static
---app
----css
----js
----img
My settings.py looks partially like this:
STATIC_ROOT = 'staticfiles'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/app'),
)
AWS_HEADERS = {
'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',
'Cache-Control': 'max-age=94608000',
}
AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']
AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
if DEBUG:
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_URL = '/static/'
else:
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
STATIC_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN
STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
What I'm trying to achieve is that if I'm running development (when DEBUG would be true) serve static files from the project, rather than fetching from S3.
At the end of my urlpatterns in urls.py I have + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT).
Finally, in my base.html I have:
<!doctype html>
...
<link rel="stylesheet" href="{% static '/css/normalize.css'%}">
If I'm running with debug=True and I view the source of the page I see <link rel="stylesheet" href="/css/normalize.css"> which isn't where the file is. If I run with debug=False and view the source I get<link rel="stylesheet" href="<AMAZON BUCKET>/css/normalize.css">.
What am I missing to serve locally?
You have to pass a relative path to the static template tag, without the heading slash:
{% static 'css/normalize.css' %}
Related
I have an issue with django. I recently bought an instance of a shared server and I wanted to move my django website from AWS to this server (which use Cpanel). All worked fine with AWS but when I switched to Cpanel all statics files were missing.
this is my settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = "/media/"
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
my project structure:
my_project
|-app/
|-...
|-views.py
|-db.sqlite3
|-manage.py
|-media/
|-my_project/
|-...
|-settings.py
|-static/
|-main_page/
|-js/
|-my-script.js
I add static files like this:
{% load static %}
<script src="{% static 'main_page/js/my-script.js' %}"></script>
This is the error:
GET http://my.domain.com/static/main_page/js/my-script.js net::ERR_ABORTED 404 (Not Found)
When I go to the URL of the file it understands it like one of my URLs:
I hope you will help me to solve this issue ;)
thanks.
you need to add the static & media files config in the urls.py , like this
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
the django docs : https://docs.djangoproject.com/en/3.1/howto/static-files/
I ran into a strange problem while deploying staticfiles to S3.
I installed boto3 and django-storages.
Django: 2.1.2
Python: 3.6.7
When running locally, my staticfiles settings were following,
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_DIR,
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
When I want to save staticfiles to S3 bucket, I changed settings to
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
AWS_ACCESS_KEY_ID = 'key'
AWS_SECRET_ACCESS_KEY = 'key'
AWS_STORAGE_BUCKET_NAME = 'name'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_STATIC_LOCATION = 'static'
AWS_MEDIA_LOCATION = 'media'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)
STATIC_ROOT = STATIC_URL
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_MEDIA_LOCATION)
MEDIA_ROOT = MEDIA_URL
STATICFILES_STORAGE = 'main.storage_backends.StaticRootS3BotoStorage'
DEFAULT_FILE_STORAGE = 'main.storage_backends.MediaStorage'
storage_backends.py
from storages.backends.s3boto3 import S3Boto3Storage
StaticRootS3BotoStorage = lambda: S3Boto3Storage(location='static')
class MediaStorage(S3Boto3Storage):
location = 'media'
file_overwrite = False
After running,
python manage.py collectstatic
I still get the following prompt,
You have requested to collect static files at the destination
location as specified in your settings:
/home/drogon/Crowdsocial_project/staticfiles
This will overwrite existing files!
Are you sure you want to do this?
It still saves to staticfiles directory locally, not on s3.
What am I doing wrong?
I followed these two tutorials,
https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html
https://www.codingforentrepreneurs.com/blog/s3-static-media-files-for-django/
I'm using Amazon S3 to be my static and media files storage. My Django project is running in Digital ocean ubuntu 16.04.
After running python manage.py collectstatic I found the CSS and js did not work in my website. And then I found that the CSS and js hadn't been upload in the S3. I think this is the reason why the cs and js did not work because they are not in there.
there is only 'static' folder in S3.
in this static folder there are not my project static files but the admin xadmin and another plug's static files
Above is the folder under static in S3.
When I check the url of the js it looks like this:
<link rel="stylesheet" href="https://myproject.s3.amazonaws.com/css/main.css?Signature=imJphDmnb4U%2BWOWHjE0Iagk2tow%3D&AWSAccessKeyId=AKIAI4LFEI2ASSMOYRTQ&Expires=1537337559">
<link rel="icon" href="https://myproject.s3.amazonaws.com/images/logo-blue.png?Signature=ACidpeC946mBazTtHx0McVIk6rM%3D&AWSAccessKeyId=AKIAI4LFEI2ASSMOYRTQ&Expires=1537337559">
But in my project the main.css is under static folder, the images are under media folder. This is so weird for me.
This is my project folder looks like:
And I found that, after running python manage.py collectstatic the system didn't copy the static and media at all
Here is the main part of my settings.py:
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))
ROOT_URLCONF = 'myproject.urls'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
AWS_ACCESS_KEY_ID = 'myproject'
AWS_SECRET_ACCESS_KEY = 'myproject'
AWS_STORAGE_BUCKET_NAME = 'myproject'
AWS_S3_FILE_OVERWRITE = False
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
# the sub-directories of media and static files
STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'
# a custom storage file, so we can easily put static and media in one bucket
STATICFILES_STORAGE = 'myproject.custom_storages.StaticStorage'
DEFAULT_FILE_STORAGE = 'myproject.custom_storages.MediaStorage'
# the regular Django file settings but with the custom S3 URLs
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
I also created a file named custom_storages.py:
from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage
class StaticStorage(S3Boto3Storage):
location = settings.STATICFILES_LOCATION
class MediaStorage(S3Boto3Storage):
location = settings.MEDIAFILES_LOCATION
I followed this tutorial https://blog.bitlabstudio.com/ultra-short-guide-to-django-and-amazon-s3-2c5aae805ce4
This issue is really very complicated to me. Any friend can help? This issue spends me 2 days to solve it.
Please help to understand what I do wrong.
I have in my settings.py :
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
STATIC_URL = os.path.join(PROJECT_ROOT, 'static').replace('\\','')+'/'
And in index.html :
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static "/css/table.css" %}">
But I still have the error 404 :
"GET /var/cardsite/cardsite/static/css/table.css HTTP/1.1" 404 1696
I have this file :
ls -la /var/cardsite/cardsite/static/css/table.css
-rw-r--r-- 1 root root 77 Sep 25 16:15 /var/cardsite/cardsite/static/css/table.css
So what is going on?
P.S. My project stored on "/var/cardsite" and I want to make static folder on each application, like in example is default application "cardsite"
thanks
Read this Django_Docs
You must also have a STATIC_ROOT option set before you can use the static files, heres some help
add this to your code:
STATIC_URL = os.path.join(PROJECT_ROOT, 'static').replace('\\','')+'/'
# Here you can add all the directories from where you want to use your js, css etc
STATICFILES_DIRS = [
# This can be same as the static url
os.path.join(PROJECT_ROOT, "static"),
# also any other dir you wanna use
"/any/other/static/path/you/wanna/use",
]
# This is the static root dir from where django uses the files from.
STATIC_ROOT = os.path.join(PROJECT_ROOT, "static_root")
you will also need to specify it in the urls.py file, just add the following code to the urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
after you add this, run the command:
python manage.py collectstatic
This will copy all the statics you need to the static root dir.
I am using Django 1.4 and for some reason i am able to serve media files, but not the static ones...
Here is my code:
settings:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
urls.py:
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_ROOT}),
base.html:
<link href="{{ STATIC_URL }}css/bootstrap.css" rel="stylesheet">
<link href="{{ MEDIA_URL }}css/bootstrap-colorpicker.css" rel="stylesheet">
i get a 404 http not found... what am i doing wrong? An i did create the static folder in my project right next to media
http://mysite.com:8000/static/css/bootstrap.css
Your static folder should be under one app that you use it for.
For example, I have a project named my_project and an application named my_app, I have some static files used in my_app so I put them under ~/project_path/my_project/my_app/static
NB: my_app must be in INSTALLED_APPS. See STATICFILES_FINDERS documentation.
Edit:
As a best practice, you should have a global static folder in one app (the main one), for example a static folder how contains your html template basic resources as jquery, bootstrap, your global style.
And for the static files how's required only for one app, for example app foo, these files should be under foo/static folder
I suggest removing the explicit media and static views and allowing the staticfiles app to create them (when DEBUG is True under development).
Check the default finders are present in your settings.py
https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#std:setting-STATICFILES_FINDERS
Either add your project static directory to STATICFILES_DIRS (https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS) or place app specific static folders under each app. The app needs to be listed in the INSTALLED_APPS for the finders to locate the static content.
Do not place static files into STATIC_ROOT yourself. This directory is managed by the collectstatic command. See https://docs.djangoproject.com/en/dev/howto/static-files/#deployment
Here is how i define my media url in settings.py:
import os
ABSOLUTE_PATH = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(ABSOLUTE_PATH, '../media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(ABSOLUTE_PATH, '../static')
STATIC_URL = "/static/"
So like you see the difference is ../media and ../static
Is mysite in your installed apps ? Django look inside your installed apps and check if there's a static folder there.