I recently upgrade Django from v1.3.1 to v1.4.
In my old settings.py I have
TEMPLATE_DIRS = ( os.path.join(os.path.dirname( __file__ ), 'templates').replace('\\', '/'), # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) This will point to /Users/hobbes3/Sites/mysite/templates, but because Django v1.4 moved the project folder to the same level as the app folders, my settings.py file is now in /Users/hobbes3/Sites/mysite/mysite/ instead of /Users/hobbes3/Sites/mysite/.
So actually my question is now twofold:
os.path to look at a directory one level above from __file__. In other words, I want /Users/hobbes3/Sites/mysite/mysite/settings.py to find /Users/hobbes3/Sites/mysite/templates using relative paths.template folder (which has cross-app templates, like admin, registration, etc.) at the project /User/hobbes3/Sites/mysite level or at /User/hobbes3/Sites/mysite/mysite?2. os.path.dirname (path) : It is used to return the directory name from the path given. This function returns the name from the path except the path name. 3. os.path.isabs (path) : It specifies whether the path is absolute or not.
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.
Python OS.Path Methods Sr.No. Methods with Description 6 os.path.lexists (path) Returns True if p ... 7 os.path.expanduser (path) On Unix and Wi ... 8 os.path.expandvars (path) Returns the ar ... 9 os.path.getatime (path) Returns the time ... 26 more rows ...
1. os.path.basename (path) : It is used to return the basename of the file . This function basically return the file name from the path given. 2. os.path.dirname (path) : It is used to return the directory name from the path given.
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 '..'.
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__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With