DJANGO - FileNotFoundError: [Errno 2] No such file or directory: '' when trying to acess a file

Viewed 3399

I'm accessing a function from a script that basically reads a JSON file and returns some value.

  • main/randomgenerator/generatorran.py
def getName():
    with open('names.json','r') as names:
             ....
  • The function works normally when executing it manually (python generatorran.py)

I'm currently importing that function and calling it when creating a model.

  • main/models.py
from main.randomgenerator import generatorran


class myModel:
    ...
    model_name = models.CharField(max_length=100,default=generatorran.getName())
  • When applying migrations it throws an error

    FileNotFoundError: [Errno 2] No such file or directory: '' when trying to acess a file

The same happens when I move the function inside of the models.py

Is there another way to read data from external files,am I missing something?

1 Answers

Django cannot find the file because the current working directory is somewhere else

to check this out add this in your python file

print os.getcwd()

as Vishal Singh said in his comment use an absolute path instead of the relative one

Related