7
self.qrcode.save
means that the whole model object needs to be saved, so it leads to a call to save
which calls generate_qrcode
which calls self.qrcode.save
… (by the way you should be able to see this in the traceback) so your problem has nothing to do with BytesIO
. Insert a condition somewhere to break the recursive loop.
2
okey here is my full solution for models.Model who works with slug field and also get_absolute_url and qr_code
class Posts(models.Model):
slug = models.SlugField(unique=True)
title = models.CharField(max_length=30)
my_qrcode = models.ImageField(upload_to='qrCode', null=True, blank=True)
def save(self, *args, **kwargs):
# we override the save method other wise, slug will not be effect and get_absolute_url will not work
if self.slug:
pass # here prevents to create slug again when updating your posts
else:
self.generate_qrcode()
super(Posts,self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('posts:detail', kwargs={'slug':self.slug})
def generate_qrcode(self):
# this part creates unique slugs
slug = slugify(self.title)
while self.__class__.objects.filter(slug=slug).order_by('-id').exists():
qs = self.__class__.objects.filter(slug=slug).order_by('-id')
new_slug = '%s-%s' % (slug, qs.first().id)
slug = new_slug
self.slug = slug
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=6,
border=0,
)
qr.add_data(self.get_absolute_url())
qr.make(fit=True)
img = qr.make_image()
buffer = StringIO.StringIO()
img.save(buffer)
filename = 'QrCode-%s.png' % (slug)
filebuffer = InMemoryUploadedFile(buffer, None, filename, 'image/png', buffer.len, None)
self.my_qrcode.save(filename, filebuffer, False) # we already have save method so just make False itself save behavior
just it, benefit of helping.
- [Django]-Dynamic (i.e. Runtime Configurable) Log Configuration for Django + Celery based application
- [Django]-Custom the `on_delete` param function in Django model fields
- [Django]-Django API Framework – Nested Models View
- [Django]-A correct case to use Django signals
- [Django]-Django urlpatterns frustrating problem with trailing slashes
Source:stackexchange.com