1

I am using Python PIL library in Django Rest Framework for building qr code and saving it to static directory.

  def generate_qr(self, name):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_M,
        box_size=15,
        border=5
    )
    qr.add_data(name)
    qr.make(fit=True)
    img = qr.make_image(fill='black', back_color='white')
    img.save(settings.STATIC_ROOT+"/asset-tags/name.png")
    return(name+ '.png')

settings.py for media and static urls:

STATIC_URL = '/static/'
STATICFILES_DIRS = (
  os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

MEDIA_URL = "/mediafiles/"
MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles")

But while saving it throws an error saying /usr/app/static/name.png : no file or directory. I am creating new file so how can it find the image in given folder.

Any Help will be appreciated. Thanks.

Viraj Kaulkar
  • 301
  • 1
  • 2
  • 15

1 Answers1

1

The qrcode package or Pillow package won't create a directory if it doesn't exist. So, as per your settings, the STATIC_ROOT is located at /staticfiles and make sure that the directory named staticfiles (and it's sub-directories) exists before runs your script.

In other words, the statement img.save(settings.STATIC_ROOT+"/asset-tags/name.png") supposed to be save the QR code image under this path /staticfiles/asset-tags/name.png and make sure the directory /staticfiles/asset-tags/ exists in your project path.

NOTE: Use settings.MEDIA_ROOT instead of settings.STATIC_ROOT would be more appropriate.

JPG
  • 82,442
  • 19
  • 127
  • 206
  • 1
    plus saving it inside `MEDIA_ROOT` would be more appropriate. `img.save(settings.MEDIA_ROOT+"/asset-tags/"+"name.png")`, will save it inside `/mediafiles/asset-tags/` – neferpitou Jul 05 '20 at 06:18