Reputation: 9868
I am trying to create a png via matplotlib but I get:
[Errno 2] No such file or directory
The same code works on unit tests. print_figure
call is in
# creates a canvas from figure
canvas = FigureCanvasAgg(fig)
filename = "directory" + os.sep + name_prefix + ".png"
# saves figure to filesystem in png format
canvas.print_figure(filename)
I am thinking it can be a permission issue, but it seems weird to me that the same code works via manage.py test
Thanks
Upvotes: 1
Views: 205
Reputation: 3027
My recommendation is to use fully qualified path names. For example: you could determine the MEDIA_ROOT from your django settings, write a snippet of code that ensures that a subdirectory for the graphs exists, then save the images there.
Your current code seems to rely on finding a subdirectory with the appropriate name in the "current working directory". The "current working directory" is a finicky thing - it will be different in testing, dev, production...
# import settings
from django.conf import settings
...
# ensure that a subdirectory with the appropriate name exists
if not os.path.exists(directory):
os.makedirs(directory)
# save the plots
canvas = FigureCanvasAgg(fig)
filename = settings.MEDIA_ROOT + os.sep + directory + os.sep + name_prefix + ".png"
# saves figure to filesystem in png format
canvas.print_figure(filename)
...
The actual location that you will save at should be determined by your needs. The key points are to use fully qualified paths and to check for the existence of the directory / subdirectory before attempting to save the image.
Upvotes: 3