Django collected static files are not accessible by templates - django

I've created a django project with some apps. Initially, I just had a single app and i had static files and templates in it. As my project grew, I added some other apps to the project which they are still accessing the statics files and templates from inside the main app. I wasn't giving much care to this problem until i tried to make a simple production and used collectstatic command. Seems i can collect my static files to the STATIC_ROOT directory but i can't access them in the templates. Here is my project structure:
shop/
-myshop(main app)
--statics
--templates
-(some other apps beside main app)
-shop(directory created by project containing settings.py, manage.py)
This is my relevant settings.py configurations:
BASE_DIR = Path(__file__).resolve().parent.parent
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
...
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / 'myshop/static',
]
STATIC_ROOT = BASE_DIR / 'static'
After running collectstatic django creates the static directory in root of project but when i remove or rename the myshop/static i get static files 404 in runserver.
I dont know how to check {% load static %} resulting path in runtime to put more information here. Is there any debug routine to understand what's django backend doing?

Try this
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
STATIC_ROOT = BASE_DIR.parent / "static_cdn"
$ python manage.py collectstatic This command will copy all files from your static folders into the STATIC_ROOT directory.
You must write the names of the static folder and the static root folder diffrent.
To learn more https://docs.djangoproject.com/en/3.1/howto/static-files/#configuring-static-files

Related

Django created staticfiles folder rather than static folder

I do not know why Django created a folder named staticfiles rather than static as expected. That might be the reason why I got an error after running python manage.py collectstatic:
The system cannot find the path specified: 'D:...\\static'
My settings file included:
from pathlib import Path
import os
import django_heroku
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
I had already tried to change 'staticfiles' to 'static' in STATIC_ROOT, but no success.
Could anyone please explain why and how to create a folder name "static"?
Thank you very much in advance!
I considered your static files are placed inside your app(s)
Try removing STATICFILES_DIRS so the setting will be:
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
...and try to re-run python manage.py collectstatic
Here is how collectstatic works:
First it collect static files from STATICFILES_DIRS if any, if there is no STATICFILES_DIRS in settings it collects static files from each app
Then placed them to STATIC_ROOT, so if your static files are placed inside your app(s) better to remove STATICFILES_DIRS
If still there is an error share your project structure

What is the correct settings for static files in django

I just started using django and I got confused over the static files. As per this post correct static files setting I understand that STATIC_URL is just like the name. STATICFILES_DIRS is the place where django will look for static files and STATIC_ROOT where the static files will be collected to. For my project I had the following file sys
rest
|__ rest
|__ settings.py
pages
static
|__admin
|__images
|__vendor
|__bootstrap
templates
manage.py
I decided to go for a project based approach when having my folders instead of a per app one. Some stuff was not working with the website landing page I had and I saw that I needed to collectstatic and so I did but I set the path to my already existing static file which did not let me at first but somehow ended up working. Out of nowhere my static folder had admin on it which I assume is from the admin app that comes with django, and my project finally started to work properly which is the confusing part. I decided to follow the post and included in my settings the following
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
Now I have a staticfiles folder along with my static folder. Also within the staticfiles folder I have everything I have in the static folder and that does not seem right and would like to know how to fix this. I am confused and a bit concerned that I will break everything again so any knowledge provided will be helpful.
I have used like this and its working fine:
STATIC_URL = '/static/'
STATICFILES_DIRS =[os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
and use to implement code in the main Project urls.py and not in-app urls.py
urlpatterns += static(settings.STATIC_URL, documents_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, documents_root=settings.MEDIA_ROOT)

Django app on Azure not getting static files

Got my Django project on a Azure webapp, but when I call on SSH terminal:
Python manage.py collectstatic
It says 252 files copied but my static files are not visible on my templates and static folder in wwwroot its empty...Here's my wwwroot structure:
wwwroot
|---Myproject
|---manage.py
|---oryx-manifest.toml
|---hostingstart.html
|---static //With all my static files
├── myapp
│ ├── migrations
│ ├── __pycache__
│ ├── static
| | |---Images
| | | |--myimage.png
| | | |--myimage2.png
│ └── templates
And this is my settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('myapp', os.path.join(BASE_DIR, 'myapp', 'static')),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Any idea why or what am I doing wrong ?, does Azure collect different ?
EDIT> When I go to my website my images don´t show...Im calling them like this on template:
{% load static %}
<img src="{% static 'Images/myimage.png' %}" /><br>
EDIT 2 /////
In wwwroot creates indeed a folder with all my statics, but when I load my template they don´t show, in wen console I get this error for myimage.png and myimage2.png :
Failed to load resource: the server responded with a status of 404 (Not Found)
Found it !!
Just had to add this: + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to url patterns like this:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('myapp/', include('myapp.urls')),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
And it did the trick, hope it helps to anyone else!!
Django does not serve static files in production mode.
The only time it serves static files is when you turn DEBUG = True which is in development mode and this is not recommended in a production setting.
Django recommends to serve static files via CND or any other webserver. However if your website is minimal and does not get high volume traffic you can serve your static files using Django whitenoise and here is how you do it.
The below solution works on python 3.7 and Django 3.2
Step 1: Install whitenoise package
pip install whitenoise
Step 2: Ensure your BASE_DIR looks like the below
BASE_DIR = Path(__file__).resolve().parent.parent
Step 3: Add these to your settings.py. If you get any errors try commenting out STATICFILES_STORAGE and check
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Step 4: WhiteNoise middleware should be placed directly after the Django SecurityMiddleware (if you are using it) and before all other middleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
Step 5: Ensure this is how you reference static files in your templates(also check if you have {% load static %} mentioned in your template
<link rel="stylesheet" type="text/css" href="{% static 'appname/styles.css' %}">
Step 6: Run collect static
python manage.py collectstatic
Step 7: Turn DEBUG = False and run the server to verify it works.
Some additional resources to read further:
whitenoise
Django on Azure - beyond "hello world"
Few points to note:
Below line will change
STATIC_ROOT = (os.path.join(BASE_DIR, 'Myproject/static_files/'))
to
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
You are using pointing to completely different folder here. Hence always empty You need the collectstatic command to copy files to
Project > static directory
Below remove the line os.path.join(BASE_DIR, 'static/')...
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/'), #Not Required since you already mentioned it in STATIC_URL
('myapp', os.path.join(BASE_DIR, 'myapp', 'static')),
)
Reason:
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.
If issue still persists check your static file directory in apache mod_wsgi config file in the server if it is configured properly.
Check this link for help on that >> https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/modwsgi/
Cheers!!!
I would recommend checking out Whitenoise for serving your static files with Django. I haven't had an issue serving them since integrating Whitenoise. Try swapping it out with your current static file finders setup.
http://whitenoise.evans.io/en/stable/django.html

404 Error for django serving static files. How to setup django to serve static files?

Settings.py file in Project directory :
I already added following :
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
-> in template
<script src="{% static "validateurl/home.js" %}"></script>
I have a directory static under project directory. home.js is under validateurl directory under static.
Referring JS File using following in template html file :
Please advise what am I missing here.
Errors below :
Here are the steps to configure your django app to serve static files for local development.
The STATIC_ROOT default is None so you have to specify that in settings. Make sure you have something like this in your settings.py This tells your webserver where to find and serve the static file mapped to a url.
import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Second also specify your STATIC_URL variable as it also defaults to none. following should suffice. This will be used for setting up the urlpattern.
STATIC_URL = '/static/'
You need to have a url pattern so your server knows what url corresponds to the static files
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Specify STATICFILES_DIRS variable in settings. So that the collect static manager knows where to find statics and put them in the STATIC_ROOT. This can be an array or tuple of items to different directories. This can be empty if you have no additional directories
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'pathtohomejsdirectory/'),)
Finally, make sure you run python manage.py collectstatic
This copies all the files specified in STATICFILES_DIRS over to the /static/ (STATIC_ROOT) directory to be served by django.
On a production, you want your webserver/reverse proxy say nginx or apache to serve the files. See here django documentation here

heroku django not collecting my static files

My question is :
When i run collectstatic command staticfiles on heroku server my app didn't copied my staticfiles ?
my configuration :
**BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))**
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env","static_root")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static_in_pro","our_static"),
Django takes the static files from STATICFILES_DIRS and static folders inside installed apps into STATIC_ROOT.
You should check for sure that you have your static files inside your folder: BASE_DIR/static_in_pro/our_static.
The simplest way is to create a static folder inside your app and than put your static files inside it . In this case, you can ignore STATICFILES_DIRS.