简体   繁体   中英

Django. How to save the generated file in FileField?

I am inexperienced in Django and I need help. I tried to override the save() method so that QR code generation and subsequent saving occurred along with it.

However, when I save the entry in the media folder, I get two files.

我的档案清单

The "17.png" file consists of the "slug" field of the model and the extension. The file is created after this line is executed:

self.qr.save(self.slug+'.png', BytesIO(qr), save=False)

The name of the other file is generated by Django itself (after creating the first file) and saves it in the "qr" field of the model. How to make sure that only one file is created (only "10.png" ) and it is saved in the field?

models.py

class Url(models.Model):
    slug = models.CharField(max_length=50, unique=True)
    qr = models.FileField(upload_to='', blank=True, null=True)

    def save(self, *args, **kwargs):
        qr = self.qr_generate(self.slug)
        self.qr.save(self.slug+'.png', BytesIO(qr), save=False)
        super(Url, self).save(*args, **kwargs)

    def __str__(self):
        return self.slug

    @staticmethod
    def qr_generate(slug):
        qr = qrcode.QRCode(
            version=None,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data("somedata" + str(slug))
        qr.make(fit=True)

        img = qr.make_image(fill_color="black", back_color="white")
        qrByte = BytesIO()
        img.save(qrByte)
        return qrByte.getvalue()

Update

Found a mistake in my code. I also redefined the form_valid method and there called save () twice. As a result, one call was removed and it became normal, the above code works

You can try something like this:

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Url)
def create_url(sender, instance, created, **kwargs):
    if created: 
        qr = instance.qr_generate(instance.slug)
        instance.qr.save(instance.slug+'.png', BytesIO(qr), save=False)
        super(Url, instance).save(*args, **kwargs)

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