Django grabing before the BASE_DIR path - django

I am trying to set my static file before the base_dir file
like,
My root dir is Desktop/afolder/projectdir/settings.py
and my current static file in Desktop/afolder/static/blabla.js
And grab it like with
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Above those works great, but now i am changing my static file dir, it will be now before the base dir
like: Desktop/static/blabla.js
In this case, i am in trouble to configure my setting so that it get my static files. coz, it is before the base dir, my base dir is afolder like Desktop/afolder/projectdir/settings.py
Can anyone help me to recognize the static file of this dir Desktop/static/blabla.js ?

Use Unipath. It gives you a convenient object-oriented approach to define paths:
from unipath import Path
BASE_DIR = Path(__file__).ancestor(2)
# Another way:
BASE_DIR = Path(__file__).parent.parent
You can install it using pip3 install unipath.

Related

Found another file with the destination path 'admin'

I am trying to deploy the app on Heroku but when I run the following command: "python manage.py collectstatic" it returns multiple "Found another file with the destination path 'admin...".
When I "git push heroku" the app, I can see the same error.
Next, the application works, but /admin page doesn't have any format, like it is not reading css, font, etc. I've checked staticfiles/admin and it has its css,font,img and js folder with files.
I've tried all the advices given here, but I'm not finding a solution. Here my settings (see my comments at the end of the code):
import os
import django_heroku
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
.
.
.
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') #Heroku
#STATIC_ROOT = os.path.join(BASE_DIR, 'static') #ok for IBM Cloud
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media') # if I comment this line and
MEDIA_URL = '/media/' # this line, /admin page has correct css but I don't have images in the application
# Extra places for collectstatic to find static files.(extra heroku)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# Next line makes application not work, it shows database errors
django_heroku.settings(locals())
"""
so, I added "release: python manage.py migrate" to procfile, now the app works,
/admin shows format ok, but database seems to be empty, no information is displayed on
site pages, and admin users don't exist anymore (my database is sqlite3).
"""
And what I get when "git push heroku master" is:
remote: Found another file with the destination path 'admin/img/selector-icons.svg'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.
remote: Found another file with the destination path 'admin/img/calendar-icons.svg'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.
.
.
.
Please help

Django template location with Cloud9

I'm learning Django and have just moved everything to Cloud9. I don't understand how to point to my templates on Cloud9?
On my local machine I have the template directory set to /home/user/etc/etc/templates and it works fine. I can't seem to grasp what the path should be when putting it in Cloud9?
It's not realy good to use absolute and hardcoded path in your projects, just because you can work on different PCs or environments. So, you can define your project path according to your settings.py file. Place this somewhere in the begining of the settings.py:
import os
PROJECT_DIR = os.path.dirname(os.path.realpath(__file__))
So now you have variable PROJECT_DIR which will point to your Django project location on every PC and every env. And now, you can use it in your project in template dirs or in static files dirs like this:
# Like this
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
# Or like this, pointing to one dir UP
TEMPLATE_DIRS += (
os.path.join(PROJECT_DIR, '../templates'),
)
Also, if you settings file containt this rows:
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.Loader',
)
Your django application will automaticaly look for templates in you applications templates dir. For example
-apps
-main_app
-templates
-blog_app
-templates
You main_app and blog app templates dirs will be detected automaticaly, without adding them to templates_path.

Why won't collectstatic copy my static files?

I have a MyApp/static/MyApp directory.
When I run ./manage.py collectstatic, I expect the MyApp directory be copied to STATIC_ROOT, but it doesn't.
I have DownloadedApp/static/DownloadedApp as well and its copied to STATIC_ROOT fine.
What am I missing?
What are the STATIC_ROOT, STATICFILES_FINDERS, and STATICFILES_DIRS in your settings.py?
When collectstatic is run, the default STATICFILES_FINDERS value django.contrib.staticfiles.finders.FileSystemFinder will collect your static files from any paths that you have in STATICFILES_DIRS.
The other default STATICFILES_FINDERS value django.contrib.staticfiles.finders.AppDirectoriesFinder will look in the /static/ folder of any apps in your INSTALLED_APPS.
All of the static files that are found will be placed in the specified STATIC_ROOT directory.
Check out this link to the collectstatic docs
And this link an explanation of the various static settings in settings.py
You can also use python manage.py findstatic to see which directories collectstatic will look in.
just do this and make the naming convention same
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
static directory contains all off your project assets
assets directory will create automatic when u run this cmd
python3 manage.py collectstatic
this will copy all static folder content into assets folder
hope this helps :)
That just happened to me and I accidentally put the app's static files directory in the .gitignore file. So on my local machine it got collected just fine, but in production the static files were actually missing (gitignored).
your are missing the STATIC_ROOT where your static files going to be copied just
add this line in your settings.py
STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles')
your settings.py looks like this :
STATIC_URL = '/static/'
STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles')
#added manully
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
remember to add STAIC_ROOT path in urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("" ,include("home.urls")),
]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
After all of it you can run :
python manage.py collectstatic
it will create a staticfiles folder for you in your Dir
This happened to me because while investigating a bug occurring on certain dates, changed my computer date and time.
Hence it disturbed things like collectstatic, and also my browser history.
Don't change your computer date and time.
I was under the impression the comparison would be content based. It turned out to be date based. So, don't mess with your files after collecstatic.
One Quick work-around, although this does not fix it or explain WHY it's happening, is to:
go to your project's file directory & rename your project's
'static' folder to something else like 'static-old'
create a new,empty folder called 'static' in your project directory
now if you run python manage.py collectstatic it will see that nothing is
in your static folder and will copy ALL static files over.
if you have setup everything properly for static and you are using nginx then enter this command
sudo nginx -t
You will see error why your static files aren't being served and fix that specific error
In my case I gave wrong path in my nginx config
location /static {
root /home/ubuntu/myproject/app/static/;
}

How to give the path for template directory

My templates are not recognized and I'm getting the following error.
os.path.dirname(__file__)+'\\template' NameError: name 'os' is not defined
The code which I have used in settings is:
os.path.dirname(__file__)+'\\template'
what should I do now.
You could see the relevant knowledge in Definitive Guide to Django Page 99:
import os.path
TEMPLATE_DIRS =(os.path.join(os.path.dirname(__file__),'templates').replace('\\','/'),)
Where explains how it works
This example uses the “magic” Python variable file, which is automatically set
to the file name of the Python module in which the code lives. It gets the name of the
directory that contains settings.py (os.path.dirname), joins that with templates in a
cross-platform way (os.path.join), then ensures that everything uses forward slashes
instead of backslashes (in the case of Windows).
Import the module os
import os
os module is missing You have used it without importing
Add this in your settings.py
import os
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)
and place all your templates under templates folder in your project
and you can use absolute paths like linux(/home/your_project/../templates) in windows ("C:/your_project/../templates")
but it is not good practice
2022 answer.
Keep templates folder in the same directory as the manage.py file
#settings.py
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = os.path.join(BASE_DIR,'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_DIR],
...

path of STATICFILES_DIRS in django

I am from PHP background and want to give path to
STATICFILES_DIRS
in settings.py and in windows I understand that I will need to give full path like:
D:/path/to/folder/project/static
I want to know that is there a way to give some path like "/static/" or can we give path like dirname(__FILE__) in PHP?
So that my path is not hardcoded. Also why it is physical path as webserver normally don't follow physical path for loading CSS files as it use http path? So why it is this way(physical path) in django? Can some one please explain.
thanks for everyone's effort in advance.
In my settings.py files, I always do
import os
ROOT_PATH = os.path.dirname(__file__)
Then you can do
STATICFILES_DIRS = [os.path.join(ROOT_PATH, 'static')]
The reason that STATICFILES_DIRS wants a filesystem path is that it needs to know where the files live in the operating system (so things like manage.py collectstatic are possible). The STATIC_URL setting is for webserver paths, and that's what it uses to show to the user in the admin or the {% static %} tag or whatever. STATICFILES_DIRS is server-side only and never shows up in any rendered templates or anything.
Find the settings.py file in the project,
Put:
STATICFILES_DIRS=(os.path.join(BASE_DIR,'static'))
Change to:
STATICFILES_DIRS=[(os.path.join(BASE_DIR,'static'))]
Answer on your question is wrong. If you do like this, you'll get the next error:
ImproperlyConfigured: Your STATICFILES_DIRS setting is not a tuple or list; perhaps you forgot a trailing comma?
My decision is add to top of settings.py file the next function:
import os
def look_folder_tree(root):
result = ()
for dir_name, sub_dirs, file_names in os.walk(root):
for sub_dir_name in sub_dirs:
result += (os.path.join(dir_name, sub_dir_name),)
return result
# Django settings for project.
PROJECT_DIR = os.path.dirname(__file__)
and call look_folder_tree function at:
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = look_folder_tree(STATIC_ROOT)
My decision is allow to add all sub folders inside static directory.
In settings.py :
Import os (already done when you create a django project)
import os
You can just use STATICFILES_DIRS as a tuple, mind the trailing comma.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Or you can use the STATICFILES_DIRS as a list data-type, comma at the end is not required here:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
Change this:
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'))
To This:
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
Add a comma at last as,
ERRORS:
?: (staticfiles.E001) The STATICFILES_DIRS setting is not a tuple or list.
HINT: Perhaps you forgot a trailing comma?
your syntax is correct, I think you forget of importing os at the first line of code as import os.
If you are using newer versions of Django i.e Django 3.1, and your BASE_DIR is like this ...
BASE_DIR = Path(__file__).resolve().parent.parent
Then do this :-
STATICFILES_DIRS =[BASE_DIR / 'my_app/static',]