[Django]-Django model error maximum recursion depth exceeded

3πŸ‘

βœ…

You copiend in wrong way from tutorial πŸ™‚

def product_post_save(sender, instance, **kwargs):
    if instance._QRCODE:
        instance._QRCODE = False
        if instance.qr_image:
            instance.qr_image.delete()
        qr = QRCode(4, QRErrorCorrectLevel.L)
        qr.addData(instance.qr_url)
        qr.make()
        image = qr.makeImage()

        #Save image to string buffer
        image_buffer = StringIO()
        image.save(image_buffer, format='JPEG')
        image_buffer.seek(0)

        #Here we use django file storage system to save the image.
        file_name = 'UrlQR_%s.jpg' % instance.id
        file_object = File(image_buffer, file_name)
        content_file = ContentFile(file_object.read())
        instance._already_saving = True
        instance.qr_image.save(file_name, content_file, save=True)

5πŸ‘

Your post save signal call save which calls the post save signal which calls save …

This is basically an infinite loop which the runtime kills with the Max Recursion error.

0πŸ‘

To solve this problem, You should add one more field in database, this field will describe that inserted record is inserted by simple view or signal. then in receiver function you should check that if instance is inserted by signal if so don’t apply receiver function

@receiver(post_save) def my_callback(using,sender,instance,**kwargs):
   if not(instance.added_by == 'signal'):
       obj = Student1()
       obj.name = instance.name
       obj.city = instance.city
       obj.state = instance.state
       obj.postal_code = instance.postal_code
       obj.age = instance.age
       obj.added_by = 'signal'
       obj.save()

0πŸ‘

My approach is just to use udpate method of QuerySet object instead of save one from Model:

Model.objects.filter(pk=obj.pk).update(fieldx=valuey)

Leave a comment