Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set STATIC_ROOT and MEDIA_ROOT so the path used is not hard coded?

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

like image 420
Ian Carpenter Avatar asked Jul 20 '14 20:07

Ian Carpenter


2 Answers

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

like image 194
wearp Avatar answered Nov 01 '22 13:11

wearp


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.

like image 26
alecxe Avatar answered Nov 01 '22 14:11

alecxe