My website was showing CSS fine until I did collectstatic - Django - python

My website was doing everything well and showing all the CSS until I ran collectstatic on it. Now everything is how it would look if CSS didn't exist. Is there any solution to this? Or is there some way I can delete the collectstatic to get back the previous thing?
I followed this tutorial to host this website: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04
Here's my settings.py(only the last bit where I set the static and the media stuff):
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATICFILES_DIRS = []
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
LOGIN_URL = '/main/user_login/'

Okay, so as you mentioned it stopped working after you ran collectstatic command.
collectstatic command makes Django looks for all static files in your apps and collects them in a single directory which is STATIC_ROOT. (In production it needs a single directory for all the static files)
Put the directories containing your static files into the STATICFILES_DIRS.
You also have to include your static urls in your urls.py
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [your paths go here]
urlpatterns += staticfiles_urlpatterns()
After including your static directories into the STATICFILES_DIRS array and including the static urls in your urls.py, use the command collectstatic and then it should work.

Related

Django serving static files even with Debug off and no web server set to serve

Based on all I've read in the docs and on various s/o questions, Django cannot serve static files in production (when DEBUG = False) and they have to be served by a web server. Yet, when I run my code my static files are showing up just fine even with debug turned off. This concerns because as we move to production, I can't imagine it will continue to serve those files without me setting it up so they're served by a web server and I don't want my dev environment to not give me an accurate picture of how it will work in production.
How is it possible that my app is serving static files without a web server with DEBUG = False? I've included the relevant blurbs in my settings.py file, urls.py file, and my command to collectstatic in my Dockerfile. It also serves the static files just fine when I have RUN python manage.py collectstatic and STATIC_ROOT commented out.
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STAT)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
STAT = os.path.join(BASE_DIR, 'static')
DEBUG = False
STATIC_URL = '/static/'
STATICFILES_DIRS = [STAT]
STATIC_ROOT = os.path.join(BASE_DIR, 'prod_static')
Dockerfile
RUN python manage.py collectstatic --noinput
Django is serving all contents of 'static' folder because of this definition:
] + static(settings.STATIC_URL, document_root=settings.STAT)
The command collectstatic does not need this definition, as it searches for all folders present in STATICFILES_DIRS and copies all static assets to your STATIC_ROOT.
Also, you should change this:
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STAT)
Like this, on development you are serving static folder with django and on production you will need a web server to serve prod_static folder.

Unexpected directories and files while using collectstatic in django

This is my django project, there is two apps; polls and study
This is the setting of my static file settings.
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,"study","static","HScard"),
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
I expected the 'python manage.py collectstatic' in the shell would copy static files to "staticfiles" from only in "study/static/HSCard"(due to STATICFILES_DIRS above).
However, "collectstatic" copied unexpected files below.
enter image description here
Why are the files in admin and polls copied to staticfiles?? besides the files in admin folder were from here (a single example):
Copying 'C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\admin\static\admin\js\vendor\xregexp\xregexp.min.js'
Why does 'collectstatic' working like this and how can I fix it as I expected?
The version of django using is 2.0.7.
Thank you.
The problem is due to the default Staticfiles Finders settings:
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
The AppDirectoriesFinder will look through your apps listed in your INSTALLED_APPS setting. If there are files such as admin/static/, which are included in the admin by default, then they will also be found by collect_static. Your choices are to either:
Remove apps from INSTALLED_APPS (obviously they won't work any more, but they won't contribute static files either)
Add the STATICFILES_FINDERS setting as above, but without the AppDirectoriesFinder setting. Then Django will only collect staticfiles that you have explicitly mentioned in STATICFILES_DIRS

Location of static files when creating a Django exe using pyinstaller

I have a Django project with the following structure:
root
videos
static
templates
and the STATIC_URL setting in settings.py is STATIC_URL = '/static/'
I managed to use pyinstaller to create a windows executable from manage.py. I can start the Django server but I can't figure out where to put the static files.
When I first started the server it could not find the templates as well, it searched for them in : 'root\django\contrib\admin\templates\videos\' I copied the templates to this folder and it worked. But I can't figure out where to put the static files. I tried putting them in 'root\django\contrib\admin\static' to recreate the original structure. But it seems it doesn't search for them there...
Anyone knows where the static files should go? Or how to define the place where a bundled pyinstaller exe will look for them ?
please see https://docs.djangoproject.com/en/1.10/howto/static-files/
in your urls.py file, you should add something like blew
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^login$', login, name='login'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
and in your app.spec file, add datas
datas=[('xxx/templates','xxx/templates'),
('xxx/static','xxx/static')],
I think I figured this one out. Like you, I was having the same issue where I could package and build my Django project with pyinstaller, but the static files could not be found when running the project from the built executable. Everything was working fine when I would run the project with manage.py, but this was a head scratcher.
The solution that worked for me was running the collectstatic function and then serving my static files from that directory instead of the app/static/app directory.
If you aren't familiar with collectstatic it essentially searches your project directory for all of the static files in your apps and puts them in a folder on your top level directory that you specify in your settings file.
Here's how to run it.
Here's a link to its documentation.
Now my top-level directory looked like this.
site
app
admin.py
apps.py
models.py
views.py
site
asgi.py
settings.py
urls.py
wsgi.py
media
media files
staticfiles
static files I want to serve (css, js, etc)
In my settings file I specified my static file settings like this...
STATIC_URL = '/staticfiles/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'app\\static\\app')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
Then in my urls.py file I included the staticfiles directory like this...
(Note this is the urls.py file in the main site directory not in the app directory if you made one in there)
from django.contrib import admin
from django.conf import settings
from django.urls import include, path
from django.conf.urls.static import static
urlpatterns = [
path('', include('app.urls')),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
In my spec file I was able to add the folder like this...
datas=[('..\\site\\staticfiles\\', '.\\staticfiles\\')]
And then in my html file I was able to use the static files like this...
<script src="{% static 'app/static.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'app/static.css' %}">
Hopefully this helps some people if they've run into the same problem. Also as a reminder be sure to run collectstatic before you build especially if you've modified or changed any of your static files.
python manage.py collectstatic
Cheers!
First make sure that django.contrib.staticfiles is included in your INSTALLED_APPS in settings.py. Then have to insert in your settings.py for example this one:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
I hope definition of BASE_DIR you have in the top of settings.py. BASE_DIR points to a folder, where your manage.py file exists. So if you would have static files in the same dir, then you leave above setting as it is. If not, let's say in the same dir, next to manage.py you will have folder named app, then your settings should look like:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "app/static"),
]
And you can even run:
python manage.py collectstatic
To get admin static files into your static directory.
Hope that helps.
This looks like it might be an issue with where the PyInstaller packed python script looks for static files. They are placed in a temporary folder and need to be accessed by an absolute path. Check out this issue: Bundling data files with PyInstaller (--onefile)

Differences between STATICFILES_DIR, STATIC_ROOT and MEDIA_ROOT

What are the differences of these three static url?
I am not sure if I am right, I am using the MEDIA_ROOT to store my uploaded photos (via models.ImageField())
However, I created a JS script to my admin and in admin.py. I defined the media as below:
....
class Media:
js = ('/admin/custom.js', )
and my settings.py:
....
STATIC_ROOT = "/home/user/project/django1/top/listing/static"
and I added the custom.js to STATIC_ROOT/admin/custom.js, but it is not working. Throwing 404 not found error.
And then I change the STATIC_ROOT to STATICFILES_DIRS, and it works!!
....
STATICFILES_DIRS = "/home/user/project/django1/top/listing/static"
So, I am not understand what is going on here. In fact, I just don't understand what is the difference between STATIC_ROOT and STATICFILES_DIRS.
Currently I am testing Django in my machine via virtualenv, not deployed yet, is it the reason STATIC_ROOT not working??
Development
STATIC_ROOT is useless during development, it's only required for deployment.
While in development, STATIC_ROOT does nothing. You don't even need to set it. Django looks for static files inside each app's directory (myProject/appName/static) and serves them automatically.
This is the magic done by manage.py runserver when DEBUG=True.
Deployment
When your project goes live, things differ. Most likely you will serve dynamic content using Django and static files will be served by Nginx. Why? Because Nginx is incredibly efficient and will reduce the workload off Django.
This is where STATIC_ROOT becomes handy, as Nginx doesn't know anything about your Django project and doesn't know where to find static files.
So you set STATIC_ROOT = '/some/folder/' and tell Nginx to look for static files in /some/folder/. Then you run manage.py collectstatic and Django will copy static files from all the apps you have to /some/folder/.
Extra directories for static files
STATICFILES_DIRS is used to include additional directories for collectstatic to look for. For example, by default, Django doesn't recognize /myProject/static/. So you can include it yourself.
Example
STATIC_URL = '/static/'
if not DEBUG:
STATIC_ROOT = '/home/django/www-data/example.com/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/'),
]
You can find these settings in the Django documentation. Here are my own definitions and quotations from the documentation:
MEDIA_ROOT is the folder where files uploaded using FileField will go.
Absolute filesystem path to the directory that will hold user-uploaded files.
STATIC_ROOT is the folder where static files will be stored after using manage.py collectstatic
The absolute path to the directory where collectstatic will collect static files for deployment.
If the staticfiles contrib app is enabled (default) the collectstatic management command will collect static files into this directory. See the howto on managing static files for more details about usage.
STATICFILES_DIRS is the list of folders where Django will search for additional static files aside from the static folder of each app installed.
This setting defines the additional locations the staticfiles app will traverse if the FileSystemFinder finder is enabled, e.g. if you use the collectstatic or findstatic management command or use the static file serving view.
In your settings, you should have:
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
# Make a tuple of strings instead of a string
STATICFILES_DIRS = ("/home/user/project/django1/top/listing/static", )
...where:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
as defined in the default Django settings.py now.
Difference between STATICFILES_DIRS and STATIC_ROOT
The STATICFILES_DIRS can contain other directories (not necessarily app directories) with static files and these static files will be collected into your STATIC_ROOT when you run collectstatic. These static files will then be served by your web server and they will be served from your STATIC_ROOT.
If you have files currently in your STATIC_ROOT that you wish to serve then you need to move these to a different directory and put that other directory in STATICFILES_DIRS. Your STATIC_ROOT directory should be empty and all static files should be collected into that directory.
MEDIA_ROOT where media files ,all uploaded files goes.
Example : Images, Files
class Media:
js = ('/admin/custom.js', )
but it is not working. Throwing 404 not found error.
The 404 error is in part because of the leading slash in the file path.

how to point to static folder in django

I am learning django and I already have a bit noobish question. I can not point to my static folder and I tried all the combinations, watched people do it in youtube tutorials etc.
My settings.py looks something like this:
STATIC_ROOT = '/home/peter/brewery/static/'
TEMPLATE_DIRS = '/home/peter/brewery/mysite/templates/'
where brewery/ is the folder containing mysite/ and static/, mysite/ is the folder created by
django-admin.py startproject
where settings.py also lives...
It seems that templates folder is mapped correctly, since the page renders with proper templates, it just cannot access the css in the /static/css/ folder. I show the path in my template for css like this
<link ... href='/static/css/brewery.css' />
I have also tried to make href absolute path on my computer and it does not work.
I am using django 1.3 and am running the server provided by django (python manage.py runserver)
1 - In your settings file, define a static url and static root like this:
STATIC_URL = '/static/'
2 - Set DEBUG = True
3 - Make sure your TEMPLATE_CONTEXT_PROCESSORS variable includes django.core.context_processors.static.
4 - Reference it in your templates like...
<link ... href='{{ STATIC_URL }}css/brewery.css' />
Source: https://docs.djangoproject.com/en/dev/howto/static-files/
In debug mode STATIC_ROOT is not used, but staticfiles_urlpatterns() provides static files from all different apps. Put your static files either into static/ directory in one of your apps or define STATICFILES_DIRS in your settings and put static files for the site there.
STATIC_ROOT is just the location where all static files are collected from all apps and STATICFILES_DIRS when you call:
python manage.py collectstatic
And it is only used in production environment.

Categories