marcos souza
marcos souza

Reputation: 761

How to use pathlib.Path in 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')

Upvotes: 3

Views: 4825

Answers (2)

Andy
Andy

Reputation: 786

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.

Upvotes: 1

thebjorn
thebjorn

Reputation: 27311

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).

Upvotes: 3

Related Questions