简体   繁体   中英

Django save image in folder

I´ve got a piece of code that creates an image using matplotlib in Django and saves it to the root directory. I need to change the folder where matplotlib saves the image to /static/img folder.

    if (len(funcion) == 2):
        plotter = plot_regions([
            [(lambda x: (matrizRestricciones[0][2]-matrizRestricciones[0]
            [0]*x)/matrizRestricciones[0][1],True),
            (lambda x: (matrizRestricciones[1][2]-matrizRestricciones[1]
            [0]*x)/matrizRestricciones[1][1],True)]], xlim=(0, 10), ylim=(0,10))
        plt.grid()
        plt.savefig("/static/img/imagen.png")
        plt.close()

Any idea how to save them there?

Thanks in advance.

Try this:

import os
from django.conf import settings

# ... your code ...
# ...
 plt.savefig(os.path.join(settings.BASE_DIR, 'static/img/imagen.png'))

Note: From your code, it appears that while you're saving the image you're not giving it a unique name. So, if you create a new image, it will replace the older image. If that is the desired behaviour, ignore this. If not, you can use uuid.uuid4 to generate unique names for your images.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM