pythondjangoqr-codedjango-signals

Django:- The QR code is being generated successfully, but it is not being saved to the database


I'm using qrcode, a Python library that enables you to generate QR codes. I want to use this Python library inside my Django signals to generate a QR code for every newly created user. However, when the user is created, it doesn't create an Account model object, and the QR code is generated inside my project directory, instead of static folder. How can I solve this problem.

signals.py:

@receiver(post_save, sender=User)
def create_account(sender, instance, created, **kwargs):
    if created:
        random_number = ''.join(random.choices(string.digits, k=20))
        img = qrcode.make('cullize')
        img.save('default.png')
        Account.objects.create(
            user=instance, qr_code=img,
            account_id=random_number
            )
class Account(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    qr_code = models.ImageField(upload_to='qrcode')
    account_id = models.IntegerField()

Solution

  • By default, my code is saving the QR code image in the current working directory. To save it in the static folder, I need to construct the path accordingly. I'm using os.path.join() to create the correct path for saving the image:

    @receiver(post_save, sender=User)
    def create_account(sender, instance, created, **kwargs):
        if created:
            random_number = ''.join(random.choices(string.digits, k=20))
            
            
            img = qrcode.make('cullize')
            
            # Define the directory where the image should be saved within the 'media' folder
            img_dir = os.path.join(settings.MEDIA_ROOT, 'qrcode')
            os.makedirs(img_dir, exist_ok=True)  # Create the directory if it doesn't exist
            
            # Define the complete path to save the image
            img_path = os.path.join(img_dir, 'default.png')
            
            # Save the QR code image
            img.save(img_path)
            
            Account.objects.create(
                user=instance,
                qr_code=os.path.relpath(img_path, settings.MEDIA_ROOT),
                account_id=random_number
            )
    

    I have updated my urls.py to include a URL pattern for serving media files:

    if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    I also updated my settings.py to include the necessary configurations for media files:

    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    

    from a particular source