whitenoise not adding random string - django

I just put up another copy of my Django app in production. The only intended difference between my "old" app and the "new" one is that the old app runs in "traditional" Heroku, and the new app runs in "Dockerized" Heroku.
The weirdest thing is happening. I use Whitenoise to serve my static assets. On the older app, links to my static assets look like this in the generated pages:
<link href="/static/assets/css/bootstrap.min.9f236e18d5bf.css" rel="stylesheet">
But on my new app, that little string (9f236e18d5bf) is missing. it looks like:
<link href="/static/assets/css/bootstrap.min.css" rel="stylesheet">
As a result, I don't have any stylesheets on my new site.
Is there an additional step that I have to take in the Dockerized version to get this to work? Or am I missing some combination of STATIC* settings values that are needed.
My temporary workaround was to add python manage.py collectstatic --noinput to Dockerfile.web, and then set:
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
Which works, but I'm wondering if I'm going to get a scaling issue on Monday.

It looks the answer comes in two parts, and I had one of each working at different times.
Be sure to have this in your Dockerfile.web:
RUN python manage.py collectstatic --noinput
CMD CMD gunicorn --bind 0.0.0.0:8000 <project-name>.wsgi
Note that you want to use RUN for your collectstatic command. Apparently only the last CMD value in a Dockerfile makes any sense.
In settings.py, have
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
That setting will cause collectstatic to add the hashes to the names of each file that is copied into the directory specified in STATICFILES_ROOT.

Related

Collectstatic deleting wagtail blog images

I have a wagtail site that I deploy using elasticbeanstalk. When I deploy collectstatic is ran:
.platform/hooks/postdeploy
#!/bin/sh
source /var/app/venv/staging-LQM1lest/bin/activate
python /var/app/current/manage.py migrate
python /var/app/current/manage.py createsu
python /var/app/current/manage.py collectstatic --noinput
I have found that this has the effect of deleting any images that are in my blog posts. I assume this is because the blog posts have been made using the page editor (of the deployed site) and are not on my local machine like the rest of the static files
How should I be setting things so that I do not delete the images everytime collectstatic is ran?
Make sure the MEDIA_ROOT and MEDIA_URL settings in your project (which define where uploaded files will be placed) are set to something different to STATIC_ROOT and STATIC_URL (which define the location of static files that are deployed as part of the app).

Compressed CSS files generated by django-compressor/libsass are not served on the first launch of the server, but are served on subsequent launches

I'm working on a Django app for the first time and I had reached a stage where I was feeling comfortable with the app's functioning in the development environment. To deploy I had to set DEBUG=False which brought some challenges. I learnt that the production servers won't serve static files the same way the development server does. I learnt the use of the py manage.py collectstatic command. I set up WhiteNoise, and upto this point I had no issues running the app in the development server with DEBUG=False. The last hurdle that remained was to serve scss files, as css. For this I used the django-libsass module. I setup the django-compressor, adding 'compressor' to list of INSTALLED_APPS, setting STATICFILES_FINDERS and COMPRESS_PRECOMPILERS as follows:
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
]
COMPRESS_PRECOMPILERS = (
('text/x-scss', 'django_libsass.SassCompiler'),
)
Finally, I updated the template with the required {% compress css %} tags. On running collectstatic I notice that the files are generated in the appropriate folder /static/CACHE/css/output.RANDOM_NUM.css. This is where the odd issue happens. The first time I run the development server, the CSS file isn't served:
WARNING - Not Found: /static/CACHE/css/output.RANDOM_NUMBER.css
The request returns a 404. This is despite me being able to verify that that file is indeed available at that path. I then shut down the server and relaunch it, and this time the page is rendered accurately and the file is served. Can anyone tell me why this is happening..?
Also, this is not an issue with the other static files which are not impacted by the django-compressor/django-libsass modules. They are served in the first launch of the server itself.
This is not a one time issue. I repeat the process again and again. 1. I delete the 'static' folder and its contents. 2. I run py manage.py collectstatic, and 3. I run py manage.py runserver. CSS not served. 4. ctrl + c and run py manage.py runserver. CSS is served. The issue repeats itself
Another thing to note is that, running py manage.py runserver --insecure does not face this issue, though I guess that is a completely different mechanism.
I'm wondering if I should ignore this, or not. The server always serves the CSS files in the second run. But the persistent nature of the issue makes me wonder if I should sort this out before deploying the app. I plan to deploy on Heroku.

Why isn't collectstatic being run automatically when I deploy my Django app to Heroku?

I've followed the official Heroku docs on Django and Static Assets; I've installed dj-static and added it to my requirements.txt file, properly configured all the variables in my settings.py file:
STATIC_ROOT = os.path.join(CONFIG_ROOT, 'served/static/')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(CONFIG_ROOT, 'static'),
)
And this is what my wsgi.py looks like:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_django_project.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
The contents of Procfile:
web: gunicorn --bind 0.0.0.0:$PORT my_django_project.wsgi:application
In the docs, it says that "collectstatic is run automatically when it is configured properly." But when I navigate to my site there's clearly no css.
I've tried debugging using heroku run, but that just copies the static files as expected.
I've noticed that when I include the collectstatic command in my Procfile, i.e.
web: python my_django_project/manage.py collectstatic --noinput ; gunicorn -b 0.0.0.0:$PORT my_django_project.wsgi:application
...that works as expected, and the static files are served.
However what's strange about that is when I run heroku run bash and look inside the directory that STATIC_ROOT is pointing to, there's nothing there! In fact, the entire served/ directory is missing, and yet, the static files are still being served!
I'd still like to know why isn't collectstatic being run automatically though -- like mentioned in the docs -- when I deploy my Django app to Heroku.
It looks like you might be using a specific settings module for Heroku/production. Further, you've set the environment variable DJANGO_SETTINGS_MODULE to point to this settings module (and that way, when the app runs, Django knows to use that one and not, say, your default/development one). Finally, you've probably configured static asset settings in Heroku/production settings module (perhaps, STATIC_ROOT).
Okay, so if this is all correct, then here is the issue: heroku environment variables are only set at serve-time, not at compile-time. This is important because collectstatic is a compile-time operation for Heroku. (Heroku goes through 2 stages when you push: 1) compiling, which involves setting the application up (collectstatic, syncdb, etc) 2) serving, the normal operation of your application).
So, essentially, you've done everything correctly, but Heroku hasn't exposed your environment variables, including your specification of a different settings module, to collectstatic.
To have your environment variables set to compile-time, enable Heroku's user-env-compile lab feature like this:
heroku labs:enable user-env-compile
I think this is a silly thing to do by default, and would be interested in hearing why Heroku thought it was a good idea.
Have you tried adding the user_env_compile setting to your heroku config?
heroku labs:enable user-env-compile
With that enabled collectstatic should be run whenever you deploy to heroku automatically.
I am using the heroku python buildpack with dokku, and collectstatic was not being run because it had no execute permission. They fixed that in a recent commit (Dec 13, 2013), so it should work now.

serve static file with herokku, django and wsgi

I was working to deploy a website to heroku. The site seems to recognize my static files if I run with django's builtin server namely "runserver". However if I run with gunicorn The static files cannot be recognized. I was wondering if there's any special setting I need to tweak to magically make the recognition happen. Can anyone enlighten me how these two commands differ specifically or does it have anything to do with wsgi staff?
Thanks!!!
This is how I do with runserver in Procfile, which is quite neat.
web:python manage.py runserver
And here's what I do with gunicorn in Procfile, which is a mess
web: gunicorn some.dotted.path.to.mywsgi:application
UPDATE
Luckily I worked around this problem by including the following line to my urls.py. Though I know it's not a perfect solution because in real word, you need to shutdown DEBUG. but as for now in development. it's working well. Can anyone explain what this line magically do?
if settings.DEBUG:
urlpatterns += patterns('django.contrib.staticfiles.views',
url(r'^static/(?P<path>.*)$', 'serve'),
)
Serving static files on Heroku with Django is a bit tricky. Assuming you're using the 'staticfiles' app, you have to run 'collectstatic' to collect your static files after deploying. The problem with Heroku is that running 'collectstatic' in the shell will actually run in a new dyno, which disappears as soon as it's finished.
One potential solution is outlined here:
Basically, the idea is to combine a few commands in your Procfile so that 'collectstatic' is run during the dyno spinup process:
web: python my_django_app/manage.py collectstatic --noinput; bin/gunicorn_django --workers=4 --bind=0.0.0.0:$PORT my_django_app/settings.py
You also have to add the 'static' views to your urls.py (see https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user, but duplicate for STATIC_URL and STATIC_ROOT). It's worth noting that the Django docs recommend against using this in production.
This solution isn't ideal though, since you are still using your gunicorn process to serve static files. IMHO the best approach to dealing with static files on Heroku is to host them on something like S3.

Heroku collectstatic not run during deployment

I have a django app that I am successfully deplying to heroku. When I dry-run the collectstatic command locally everything works fine.
python manage.py collectstatic --dry-run --noinput
....
Pretending to copy '/Users/hari/.virtualenvs/bsc2/lib/python2.7/site-packages/django/contrib/admin/static/admin/js/admin/ordering.js'
Pretending to copy '/Users/hari/.virtualenvs/bsc2/lib/python2.7/site-packages/django/contrib/admin/static/admin/js/admin/RelatedObjectLookups.js'
71 static files copied.
Despite this ..my django admin staticfiles do not get used and I get a bare-bones django admin site on heroku with Debug set to False.
If I set Debug to True I get a "rich" admin site on heroku. With Debug set to True or False "git push heroku master " command terminal output does not have anything about collecting staticfiles.
I tried the example "helloworld" application that uses gunicorn from Heroku and that did display the "collecting static" messages.I also tried inserting this code snippet into my urls.py. But that too does not help.
from django.conf import settings
if not settings.DEBUG:
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
Next, I tried adding the following to my heroku config
heroku config:add DISABLE_COLLECTSTATIC=0
But that too did not show my django admin site with all the styles.
Finally I tried switching to gunicorn with my Procfile and that also did not show the admin styles. Only setting Debug=True works to show my admin styles.
I tried this with Django 1.4.2 and 1.5.1 on Heroku and neither is showing me a "normal" admin site. Is there any way out to have my admin files on heroku without going the S3 route.
command terminal output does not have anything about collecting staticfiles.
Looking at heroku-buildpack-python:bin/steps/collectstatic it seems that it tries to do a collectstatic --dry-run --noinput and pipes it's output to /dev/null before displaying the -----> Collecting static files message. This means that if there is an error there that is not present on your local box, you will never see the error on heroku : it will silently fail. (The best kind of failure ;)
have you tried running a one-off worker to test out the collectstatic command and see if it's a problem in their environment?
heroku run python manage.py collectstatic --dry-run --noinput
If this fails, it will give you an error or traceback to look into and further diagnose the issue.
Check this out Django and Static Assets. It seems to be updated recently and you can serve static files nicely using this dj-static package.
Try these three things:
Create this Heroku config variable: DJANGO_SETTINGS_MODULE with a
value of myapp.settings.prod--or as appropriate for your Heroku settings file
Use Whitenoise as described in the Heroku docs:
https://devcenter.heroku.com/articles/django-assets
Check it in and redeploy your dyno: git push heroku master
I found I was missing the first item, the DJANGO_SETTINGS_MODULE" e.g., Command line collectstatic would work but that didn't matter b/c it was an ephemeral dyno
throwing it out there, since dumb mistakes happen:
I spent much time trying to figure out why my module wasn't found on heroku when it was working fine locally, only to realize it was ignored by an entry into .slugignore