How to give the path for template directory - django

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],
...

Related

Can't find files in django

I'm trying to work with some json and csv files in my django project but it never found they.
I created a static folder and inside it I have create a new one called data with the different files. But when I call it, the message is always the same, it can't found the path of my files.
[Errno 2] File b'data/data.csv' does not exist: b'data/data.csv'
Inside settings.py I have this:
STATIC_URL = '/static/'
STATICFILES_DIRS =[
os.path.join(BASE_DIR, 'static'),
]
Somebody knows what I'm doing wrong?
An example how I call my csv file:
def dataframex():
data_csv = pd.read_csv('data/data.csv')
print(data_csv)
Thank you!
pandas.read_csv() has no idea about Django's staticfiles configuration.
Assuming you're using local static files and not e.g. something backed by S3 or something more esoteric, you can use finders.find() to locate the real file on disk:
from django.contrib.staticfiles import finders
def dataframex():
csv_path = finders.find('data/data.csv')
data_csv = pd.read_csv(csv_path)
print(data_csv)
However, for static files you don't need to directly serve to the user, such as this one, it's better to just store them in your application directory.
Assuming myapp/views.py contains the above, you can move data.csv to myapp/data.csv, then use
csv_path = os.path.join(os.path.dirname(__file__), 'data.csv')
to locate the file.

Django grabing before the BASE_DIR path

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.

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.

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',]

Django paths, developing in windows, deploying on linux

I'm developing Django apps on my local windows machine then deploying to a hosted linux server. The format for paths is different between the two and manually replacing before deployment is consuming more time than it should. I could code based on a variable in my settings file and if statements but I was wondering if anyone had best practices for this scenario.
The Django book suggests using os.path.join (and to use slashes instead of backslashes on Windows):
import os.path
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)
I think this is the best solution as you can easily create relative paths like that. If you have multiple relative paths, a helper function will shorten the code:
def fromRelativePath(*relativeComponents):
return os.path.join(os.path.dirname(__file__), *relativeComponents).replace("\\","/")
If you need absolute paths, you should use an environment variable (with os.environ["MY_APP_PATH"]) in combination with os.path.join.
We have a situation very similar to yours, and we've been using different paths in settings, basing on sys.platform.
Something like this:
import os, sys
DEVELOPMENT_MODE = sys.platform == 'win32'
if DEVELOPMENT_MODE:
HOME_DIR = 'c:\\django-root\\'
else:
HOME_DIR = '/home/django-root/'
It works quite OK - assumed all development is being done on Windows.
Add
import os.path
BASE_PATH = os.path.dirname(__file__)
at the top of your settings file, and then use BASE_PATH everywhere you want to use a path relative to your Django project.
For example:
MEDIA_ROOT = os.path.join(BASE_PATH, 'media')
(You need to use os.path.join(), instead of simply writing something like MEDIA_ROOT = BASE_PATH+'/media', because Unix joins directories using '/', while windows prefers '\')
in your settings.py add the following lines
import os.path
SETTINGS_PATH = os.path.abspath(os.path.dirname(__file__))
head, tail = os.path.split(SETTINGS_PATH)
#add some directories to the path
import sys
sys.path.append(os.path.join(head, "apps"))
#do what you want with SETTINGS_PATH