394๐
os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'templates'))
As far as where the templates folder should go, I donโt know since Django 1.4 just came out and I havenโt looked at it yet. You should probably ask another question on SE to solve that issue.
You can also use normpath
to clean up the path, rather than abspath
. However, in this situation, Django expects an absolute path rather than a relative path.
For cross platform compatability, use os.pardir
instead of '..'
.
152๐
To get the folder of a file just use:
os.path.dirname(path)
To get a folder up just use os.path.dirname
again
os.path.dirname(os.path.dirname(path))
You might want to check if __file__
is a symlink:
if os.path.islink(__file__): path = os.readlink (__file__)
- [Django]-Django: Using F arguments in datetime.timedelta inside a query
- [Django]-Django 2, python 3.4 cannot decode urlsafe_base64_decode(uidb64)
- [Django]-Override existing Django Template Tags
94๐
If you are using Python 3.4 or newer, a convenient way to move up multiple directories is pathlib
:
from pathlib import Path
full_path = "path/to/directory"
str(Path(full_path).parents[0]) # "path/to"
str(Path(full_path).parents[1]) # "path"
str(Path(full_path).parents[2]) # "."
- [Django]-How do you dynamically hide form fields in Django?
- [Django]-Is it bad to have my virtualenv directory inside my git repository?
- [Django]-Embedding JSON objects in script tags
25๐
You want exactly this:
BASE_DIR = os.path.join( os.path.dirname( __file__ ), '..' )
- [Django]-Ignoring Django Migrations in pyproject.toml file for Black formatter
- [Django]-Django models: mutual references between two classes and impossibility to use forward declaration in python
- [Django]-Embedding JSON objects in script tags
13๐
Personally, Iโd go for the function approach
def get_parent_dir(directory):
import os
return os.path.dirname(directory)
current_dirs_parent = get_parent_dir(os.getcwd())
- [Django]-Django REST Framework: how to substitute null with empty string?
- [Django]-Are sessions needed for python-social-auth
- [Django]-Django admin default filter
12๐
If you prefer a one-liner for getting the parent directory, Iโd suggest this:
import os
parent_dir = os.path.split(os.getcwd())[0]
os.path.split()
method returns a tuple (head, tail) where tail is everything after the final slash. So the first index is the parent of your absolute path.
- [Django]-Constructing Django filter queries dynamically with args and kwargs
- [Django]-RuntimeWarning: DateTimeField received a naive datetime
- [Django]-Separation of business logic and data access in django
9๐
I think the easiest thing to do is just to reuse dirname()
So you can call
os.path.dirname(os.path.dirname( __file__ ))
if you file is at /Users/hobbes3/Sites/mysite/templates/method.py
This will return โ/Users/hobbes3/Sites/mysiteโ
- [Django]-Django Rest Framework โ Updating a foreign key
- [Django]-How to mix queryset results?
- [Django]-Django datetime issues (default=datetime.now())
7๐
from os.path import dirname, realpath, join
join(dirname(realpath(dirname(__file__))), 'templates')
Update:
If you happen to โcopyโ settings.py
through symlinking, @forivallโs answer is better:
~user/
project1/
mysite/
settings.py
templates/
wrong.html
project2/
mysite/
settings.py -> ~user/project1/settings.py
templates/
right.html
The method above will โseeโ wrong.html
while @forivallโs method will see right.html
In the absense of symlinks the two answers are identical.
- [Django]-Stack trace from manage.py runserver not appearing
- [Django]-Problems extend change_form.html in django admin
- [Django]-Django Template Language: Using a for loop with else
7๐
This might be useful for other cases where you want to go x folders up. Just run walk_up_folder(path, 6)
to go up 6 folders.
def walk_up_folder(path, depth=1):
_cur_depth = 1
while _cur_depth < depth:
path = os.path.dirname(path)
_cur_depth += 1
return path
- [Django]-Django Model() vs Model.objects.create()
- [Django]-Create custom buttons in admin change_form in Django
- [Django]-Data Mining in a Django/Postgres application
5๐
Go up a level from the work directory
import os
os.path.dirname(os.getcwd())
or from the current directory
import os
os.path.dirname('current path')
- [Django]-NumPy array is not JSON serializable
- [Django]-Celery : Execute task after a specific time gap
- [Django]-Custom django admin templates not working
4๐
To go n
folders upโฆ run up(n)
import os
def up(n, nth_dir=os.getcwd()):
while n != 0:
nth_dir = os.path.dirname(nth_dir)
n -= 1
return nth_dir
- [Django]-In Django 1.4, do Form.has_changed() and Form.changed_data, which are undocumented, work as expected?
- [Django]-Altering one query parameter in a url (Django)
- [Django]-'staticfiles' is not a valid tag library: Template library staticfiles not found
3๐
Iโm surprised handling for an arbitrary number of ".." parent directory tokens in a path string isnโt directly handled for by the os library. Hereโs a quick and dirty function thatโll give you an absolute path string from a relative one:
def get_abs_from_relpath(relpath:str) -> str:
ap = os.path.abspath(__file__).split("/")[:-1]
sp = relpath.split("/")
sp_start_index = 0
for slug in sp:
if slug == "..":
ap.pop(-1)
sp_start_index += 1
else:
return "/".join(ap+sp[sp_start_index:])
You can call it with open() like this:
with open(get_abs_from_relpath('../../../somedir/myfile.txt')) as f:
foo = f.read()
- [Django]-Django โ Annotate multiple fields from a Subquery
- [Django]-CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true
- [Django]-What is a django.utils.functional.__proxy__ object and what it helps with?
2๐
For a paranoid like me, Iโd prefer this one
TEMPLATE_DIRS = (
__file__.rsplit('/', 2)[0] + '/templates',
)
- [Django]-How can I activate the unaccent extension on an already existing model
- [Django]-Explicitly set MySQL table storage engine using South and Django
- [Django]-Suppress "?next=blah" behavior in django's login_required decorator
2๐
With using os.path
we can go one directory up like that
one_directory_up_path = os.path.dirname('.')
also after finding the directory you want you can join with other file/directory path
other_image_path = os.path.join(one_directory_up_path, 'other.jpg')
- [Django]-Referencing multiple submit buttons in django
- [Django]-Uwsgi installation error in windows 7
- [Django]-Django F() division โ How to avoid rounding off
1๐
From the current file path you could use:
os.path.join(os.path.dirname(__file__),'..','img','banner.png')
- [Django]-Django JSONField inside ArrayField
- [Django]-How can I see the raw SQL queries Django is running?
- [Django]-Django multiple template inheritance โ is this the right style?
- [Django]-Why does Django's render() function need the "request" argument?
- [Django]-How to test auto_now_add in django
- [Django]-Django form fails validation on a unique field
0๐
Not an answer but a long tangential comment that probably should be made as someone may be led astrayโฆ
The syntax os.path.join( os.path.dirname( __file__ ), 'foo.txt')
to get a file within the same folder as the python file getting run is not the "advised" solution for packages, instead package data is preferred for a couple of reasons, for example in a zip packaged package or a more complicated filesystem.
pkg_resources.read_text(__package__, 'foo.txt')
was the formerly recommended solution, but will be removed at some point and importlib.resources.read_text(__package__, 'foo.txt')
is the recommended way โsee https://docs.python.org/3/library/importlib.html#module-importlib.resources for the many options.
However, this
- requires
include_package_data=True
andpackage_data
with aDict[str, List[str]
in thesetup.py
file - requires a
MANIFEST.in
if pip distributed as sdist (but not a built wheel) - will not work for relative imports (i.e. not installed)
- is wisely and generally ignored for sake of sanity in webapps due to the way they run
- [Django]-How to loop over form field choices and display associated model instance fields
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
- [Django]-Django-Bower + Foundation 5 + SASS, How to configure?