lincolnloop / python-qrcode

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

How to save qrcode to database python3 django #180

Closed softwareEng92 closed 4 years ago

softwareEng92 commented 5 years ago

I created a table for products and its have an ImageField like this: productQrImage = models.ImageField(upload_to='media/', blank=True, null=True)

and that is my code for generate a qrcode and it takes product name (as you can see down). its save png file to media its ok but I need to save it to database and than retrieve to product list page. I search for this about two days I haven't find any solution.

   qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=5,
            border=4,
        )

        qrName = request.POST.get("productName")
        s = "http://127.0.0.1:8000/products/" + qrName
        qr.add_data(s)
        qr.make(fit=True)
        # qrPath = 'mystatic/media/' + qrName + '.png'
        img = qr.make_image(fill_color="black", back_color="white")
        img.save('mystatic/media/' + qrName + '.png')
bilalhussain8473 commented 4 years ago

Dear i need your code can you send me Bilalamjad837@gmail.com

thommath commented 4 years ago

I would either save the path in the database or store the image in the database.

To store the path just add a string to your model, if you want to save the image you can save the binary image bu first saving it to a buffer and get the binary data.

img = qrcode.make("Some text")
buf = io.BytesIO()
img.save(buf, "PNG")
contents = buf.getvalue()
SmileyChris commented 4 years ago

Good answer, @thommath (and this isn't really a core issue, so closing)