hi I have a problem when I upload a file to the deployed server. It returns 404 does not matter if I do it by admin or by a view but if I can see the files that are already on the server.
I am hosting my app in namecheap on a shareserver and the settings are
settings.py
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'static-server')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# Media folder for database media
MEDIA_URL = '/static-server/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, '/static-server/media')
url.py
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT, show_indexes=True)
switch between debug mode true or false on local and it works perfectly but not when I deploy ... if anyone has any ideas. Well, from namecheap support they answered that the error is not on their side
Django does not serve media or static files in production as it just means to save the link for it. You need to use other services as Amazon Web Services S3 Bucket to serve it. But if you want to serve it anyway you can do in using Whitenoise.
First pip install whitenoise and then pip freeze > requirements.txt
Then in settings.py
MIDDLEWARE = [
# 'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
then add this line
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
then push this code to your production server and make sure you run collectstatic command i.e python manage.py collectstatic your static files now should be working.
Related
I have just deployed (first time ever) a Django project to a web server. Everything (including postgres) works flawlessly, except that static images won't load.
Here is the relevant part of the settings.py:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
#STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "static"),
#]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_REDIRECT_URL = 'home'
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
AUTH_USER_MODEL = 'account.CustomUser'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
The error message I get is the following in the console:
"GET /static/images/logo.png HTTP/1.1" 404 1808
However, when checking the file path in the console I have the following:
root#melius:/django/melius/static/images#
In this folder the files are present.
Where is my mistake?
There can be two reaon your static files not working.
First of all, Django doesn't serve static files on production.
Also i notice your static settings are wrongly configured.
Make sure your setting.py is look like this:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'YOUR STATIC FILE FOLDERS')]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
If you run your application on Nginx or apache2please make sure you configured the.conf` file properly to serve the static files.
Also, there is a straightforward and easy solution, that is whitenoise
If you don't want to serve your static files with Nginx or a similar server.
You can try whitenoise
To use whitenoise, please install it first and update your settings.py file like this:
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
and add this in middlware before the sessionmiddleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # Serve static in production without nginx or apache
'django.contrib.sessions.middleware.SessionMiddleware',
........
]
Hope the solution will solve your problem
Here you go for whitenoise docs: http://whitenoise.evans.io/en/stable/
Note: static root and static dirs shound't be same
I'm trying to upload my project via pythonanywhere but I always get failed to load static files I tried to download it by the static files section of web tab that exists into pythonanywhere and also I got failed you can see what I did here, I will show you all details that I did to help you to understand what could you give me the help through it:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# STATIC_ROOT = "/home/abdelhamedabdin96/website/website/static/index"
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# MAIN_DIR = os.path.dirname(os.path.dirname(__file__))
# STATICFILES_DIRS = (
# os.path.join(MAIN_DIR, 'static'),
# )
and in urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It seems like you haven't run collect static command, You need to run this command
python manage.py collectstatic
Here its explanation for more info vist to the django official docs
django.contrib.staticfiles collects static files from each of your applications (and any other places you specify) into a single location that can easily be served in production.
Try use Aws console and its very cheap. I see bugs on Pythonanywhere. ie. Scheduler and a lot of limitations.
Update: looks like this is being cause by the django-heroku package and specifically the inherited whitenoise package, which in docs says your supposed to put
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
at the end of settings file, which I never did but it still enforces root being 'staticfiles' folder instead of assets folder
Original Post:
When I run python manage.py collectstatic it saves to a folder called staticfiles
I must have done something to make this happen, but I've searched for staticfiles and found no reference to it except 'django.contrib.staticfiles'.
Here is my settings.py:
INSTALLED_APPS = [
#some apps
'django.contrib.staticfiles',
#some more apps
'tz_detect',
]
# some more code
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
VENV_PATH = os.path.dirname(BASE_DIR)
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(VENV_PATH, 'media_root')
Expected outcome was for when python manage.py collectstatic is run, that an assets folder would be created, but this never happens.
The staticfiles folder in addition to files from static folder also contains a tz_detect folder (from static assets from 3rd party package), an admin folder, and a staticfiles.json
middleware section of settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# some more middleware
'tz_detect.middleware.TimezoneMiddleware',
]
It appears that it isn't possible to change the name of your STATIC_ROOT using django_heroku, without monkey patching the package.
The line django_heroku.settings(locals()) takes all the local variables (ie STATIC_ROOT) and passes them into the settings function found at django_heroku/core.py.
If you take a look at line 89:
config['STATIC_ROOT'] = os.path.join(config['BASE_DIR'], 'staticfiles')
You will see that whatever value you set for STATIC_ROOT, the package will override it with staticfiles.
Note that the following may have unintended consequences, and you shouldn't do them.
Here are 2 monkey patch solutions:
change the value of STATIC_ROOT after you call django_heroku.settings(locals()):
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
modify django_heroku/core.py line 89: to the following:
if 'STATIC_ROOT' not in config:
config['STATIC_ROOT'] = os.path.join(config['BASE_DIR'], 'staticfiles')
this will prevent djano_heroku from overriding the STATIC_ROOT if you have already defined it.
Again, I don't recommend doing this because there might a good reason that Heroku forces you to use the name staticfiles, and this might cause your server to break, or worse, parts of your server might silently fail (which means debugging will be a nightmare).
when I access to my admin dashboard in Django, it doesn't load css and img files, so doesn't work well.
All the files are in 'project/static/admin', and in my settins.py I have this:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
When I execute collectstatic, appears: 0 static files copied to '/opt/myenv/myenv/static', 318 unmodified.
I'm using Nginx + Gunicorn, also I'm using https with Cloudflare.
Can anyone help me?
Thanks.
You run collectstatic with STATIC_ROOT set up
If you do not have this in your settings.py , add it
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
I recently deployed a Django app to Heroku and uploaded some media files and everything seemed to work fine, until yesterday when i tried to access the application again and saw that it was giving a 404 error.
Any ideas why this is happening?
settings.py:
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
import dj_database_url
#DATABASES['default'] = dj_database_url.config()
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
urls.py
urlpatterns = patterns('',
(r'', include(application.urls)),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
(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}),
)
Heroku dynos are of limited lifespan, and when they die and get replaced (which happens automatically) any files within them are lost, including any files you uploaded via Django. What you want to do is to set up Django's media handling to put the files somewhere more permanent (which will also allow you to use multiple dynos at once, which is how Heroku tackles horizontal scaling). I tend to use Amazon S3 for this, so my configuration looks a little like:
AWS_STORAGE_BUCKET_NAME = "your_bucket"
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
MEDIA_URL = "https://%s.s3.amazonaws.com/" % os.environ['AWS_STORAGE_BUCKET_NAME']
MEDIA_ROOT = ''
AWS_ACCESS_KEY_ID = "your_access_key_id"
AWS_SECRET_ACCESS_KEY = "your_secret_access_key"
This is using django-storages and boto to provide a Django storage layer using Amazon S3.
Note that this "pass-through" access for S3 may be inappropriate depending on your application. There are some notes on working with S3 in Heroku's devcenter that may help.
My guess would be that something is off with your static files.
For example, you have
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
For my Heroku app, I have
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Settings for static files is something that few people seem to really understand (including myself), but this blog post offers a pretty good explanation: http://blog.doismellburning.co.uk/2012/06/25/django-and-static-files/