BASE_DIR vs os.join()

Hi I´m new to django. I have seen two different methods for letting django know where to look for the templates. Some people use os.join() method to concatenate the path but I have just written

‘DIRS’: [BASE_DIR / ‘templates’],

and it works. I didn´t import os or something. What is the right way to do it or is it just personal preference. As I understand it the BASE_DIR is always refering to the Project folder. thanks for answers.

The default settings file changed in Django 3.1 to define BASE_DIR as a pathlib Path, instead of as a string. I wrote a post at the time: Use Pathlib in Your Django Settings File - Adam Johnson

This is why some old projects use os.path.join(), whilst you’re able to use the / operator! :sunglasses:

1 Like

in regard to “what is the right way to do it?”, It’s either I think, no right way, whichever way you want as both ways still work. I don’t know if something will change in Django 4.2 though.

I tend to use os.path.join(settings.BASE_DIR) in other custom scripts when I want to get the path of different files such as images in my media folder. I also use this for generating URLs in a crafty way for example:

image_url = str(os.path.join(settings.BASE_DIR) + str(image_list[0])).replace('\\','/')

you can import your settings.py into other scripts with:

from django.conf import settings

1 Like