5

In my settings.py file both the STATIC_ROOT and MEDIA_ROOT both currently point to a hard coded location. For example the STATIC_ROOT path is:

/home/ian/projectname/mysite/appname/static

I know this will cause problems when I deploy my project.

Looking around I can see that I need to make use of os.path but the countless examples have just confused me.

I have tried to view different permutations of setting this file (or getting the example value as used to set the BASE_DIR) however as the screen shot shows I am missing something because it is complaining about the file value.

In case of need I am using Django 1.6

Thanks in advance.

enter image description here

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Ian Carpenter
  • 8,346
  • 6
  • 50
  • 82

2 Answers2

5

Firstly, you are receiving this error as a result of appending the __file__ in interactive shell:

NameError: name '__file__' is not defined

The shell doesn't detect the current file path in __file__ as it relates to your filepath in which you added this line. To work, for example, you will need to include this in file.py:

os.path.join(os.path.dirname(__file__))

Then, run this from the command line:

python file.py

This is because __file__ relates to whatever the filepath of file.py is.

In the case of settings.py, use this to get the root directory of your Django project:

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

You can then use os.path.join() to join other relative paths, such as:

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
TEMPLATE_DIRS = os.path.join(BASE_DIR, 'templates')

For more information on how to lay out your Django project directory, read this: Common structures

Eje
  • 354
  • 4
  • 8
wearp
  • 153
  • 1
  • 9
3

The usual practice (suggested in django official tutorial also) is to have a BASE_DIR setting that gets the current working directory from the __file__:

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

Then, using os.path.join() other relative paths are constructed, for example:

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

Note that __file__ is only available for the module, it doesn't make sense to use it on a console.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Thanks for the very prompt response, using the example of BASE_DIR, if I was able to see its value would it be "/home/ian/projectname/mysite/"? If so how do I use os.path.join to go another two folders down? i.e. /appname/static ? – Ian Carpenter Jul 20 '14 at 21:08
  • @IanCarpenter well, usually static root is on the project level, not app level. If you have multiple apps with their own static files - use `staticfiles` built-in app, see more at [Managing static files](https://docs.djangoproject.com/en/dev/howto/static-files/). – alecxe Jul 20 '14 at 23:01