0
'DIRS': [os.path.join(
      os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'templates')],

resolves to:

'/opt/python/current/app/src/myproject/templates'

What change would I need to make to may code to get DIRS to resolve to the following?

'/opt/python/current/app/src/templates'
Cfreak
  • 19,191
  • 6
  • 49
  • 60
Jason Howard
  • 1,464
  • 1
  • 14
  • 43

3 Answers3

1

pathlib can make this easier. Its like os.path but implemented as a class suitable for method chaining.

from pathlib import Path

filename = "would be nice if OP gave us the test input"
templates = Path(filename).absolute().parents[2].joinpath('templates')

templates is still a Path object. Some API's accept Path but you can also do templates = str(templates) to get the path string.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
1

Since os.path.dirname gets the directory name for a specified file (in your case __file__, you can see what this means int here) you will get the parent directory of that file.

Now os.path.abspath gets the absolute path of the current working directory with the file name.

And last os.path.join works by joining two paths. For example, if you have are located in /opt/python/current/app/src/myproject/ and you want to join the templates folder to that path you do os.path.join(/opt/python/current/app/src/myproject/,templates)

so to get what you need you to do to get what you need

'DIRS' : [os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))),
'templates')
],

os.path.abspath gets the absolute normalized path of __file__ then it gets the parent directory with first os.path.dirname (innermost) and the second gets that resultant path parent directory and so on.

If by using two os.path.dirname you get /opt/python/current/app/src/myproject/templates that means you need one more os.path.dirname to achieve what you want.

corlo
  • 19
  • 3
0

print(os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(file))), "templates"))