Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended way of accessing BASE_DIR in Django

Tags:

python

django

I am coding an automated menu module in Django that will list all the packages in BASE_DIR that have a urls.py file. For this I obviously need to access BASE_DIR, but I haven't been able to find a standard way of doing this. I could just do:

from myproject import settings

do_stuff(settings.BASE_DIR)

but I'd rather not hardcode it to myproject since this menu module could also be used for other applications. Is there a better solution?

like image 826
Lundis Avatar asked Oct 07 '14 08:10

Lundis


2 Answers

This isn't a question about BASE_DIR, but about importing settings. Your proposed solution is not valid Python in any case: imports don't use file paths like that.

The standard and fully documented way of importing settings in Django is this:

from django.conf import settings

This will always work, in any Django project, and will allow you to access any of the settings.

like image 86
Daniel Roseman Avatar answered Oct 21 '22 12:10

Daniel Roseman


For example, in a views.py file, we can do the following to use the value of BASE_DIR

from django.conf import settings
value = settings.BASE_DIR
like image 2
Ariful Haque Avatar answered Oct 21 '22 12:10

Ariful Haque