lincolnloop / python-qrcode

Python QR Code image generator
https://pypi.python.org/pypi/qrcode
Other
4.36k stars 666 forks source link

Saving PNG QR code from views.py #215

Closed wecoon closed 3 years ago

wecoon commented 3 years ago

Hi all, I tried all options, but couldn't make it work. Now I'm trying to save QR code as .png as documented, but still no luck. Here is my code, maybe someone could help me get back on the track:

models.py

class PinModel(models.Model):
    pin = models.CharField(max_length=6, unique=True)
    user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE)
    qr = models.ImageField(upload_to='qr', blank=True, null=True)

    class Meta:
        unique_together = ('pin', 'user')

views.py

import qrcode
from qrcode.image.pure import PymagingImage

class PinView(viewsets.ModelViewSet):
    queryset = PinModel.objects.all()
    serializer_class = PinSerializer

    def create(self, request, *args, **kwargs):
        pin = uuid.uuid4().hex[:6].upper()
        while PinModel.objects.filter(pin=pin).count() > 0:
            pin = uuid.uuid4().hex[:6].upper()

        user = CustomUser.objects.get(id=request.data['user'])

        img = qrcode.make(pin, image_factory=PymagingImage)
        img.save('test.png')

        pin_post = PinModel.objects.create(pin=pin, user=user, qr=img)
        serializer = PinSerializer(pin_post)
        return Response(serializer.data, status=status.HTTP_200_OK)

I think I could be just blind today, but I get AttributeError: 'str' object has no attribute 'write' error in this case. Documentation does not show img.save('') line, but without it, I get AttributeError: 'PymagingImage' object has no attribute '_committed' which makes sense.

What I could be doing wrong? Thanks, everyone

saadmustafa12 commented 3 years ago

Hi! Below is a working Python program for saving PNG of QR Code

import qrcode

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data('Some data')
qr.make(fit=True)

img = qr.make_image(fill_color="black", back_color="white")

img.save("geeks.png")