Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use pathlib.Path in Django?

Tags:

python

django

I'm using pathlib.Path as an alternative to os.path, and I'm trying to use it for the directory paths in the django project, but how much do I try to create migrations, the error occurs:

"return database_name == ': memory:' or 'mode = memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable "

And my base dir:

BASE_DIR = Path(__file__).parent.parent.parent

Database join:

BASE_DIR.joinpath('db.sqlite3')
like image 439
marcos souza Avatar asked Jan 29 '26 10:01

marcos souza


2 Answers

pathlib.Paths are not strings (or bytes). Most internal Django code uses the os.path functions, and those require strings/bytes, and code that expects a string (like it looks like database_name is expecting) cannot work with pathlib.Path objects -- you'll need to convert it to string (ie. str(BASE_DIR.joinpath('db.sqlite3')

It's possible to write a Path class that is a subclass of str, which makes interaction with code that expects string much more transparent (many have created such classes, including me: https://github.com/datakortet/dkfileutils/blob/master/dkfileutils/path.py).

like image 122
thebjorn Avatar answered Jan 31 '26 01:01

thebjorn


Your use case can even be a little simpler:

BASE_DIR = Path.cwd()
DATABASE.NAME = str(BASE_DIR / "db.sqlite3")

Note: The conversion to a string, because Django can't yet handle Pathlib instances.

like image 35
Andy Avatar answered Jan 31 '26 01:01

Andy