save_formset for StackedInline not working

393 views Asked by At

I am trying to generate a qr code to assign to an image field. I have done this with no trouble on another model, using the save_model function in ModelAdmin. Now, I need to do it in an Inline. Apparently, save_model does not work here, and I am told that save_formset is the way to go instead, however I cannot get it to work. I have compared my code to other instances of save_formset which I have seen, and cannot see any syntax errors, but django will not give me an error report so I have nothing else to go on.

class InstrumentAdmin(admin.ModelAdmin):
    inlines = [
        AssetInline,
    ]
    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for f in instances:
            # save the object first so we get an id number etc.
            f.save()
            # determine the URL
            url='{}{}'.format(HOMEURL,f.get_absolute_url())
            # build a qr code
            qr = qrcode.QRCode(box_size=3)
            qr.add_data( 'FloWave TT {} {}'.format(f,url))
            qr.make(fit=True)
            img=qr.make_image()
            # save to memory
            img_io= StringIO.StringIO()
            img.save(img_io,'PNG')
            img_file=InMemoryUploadedFile(img_io, None, 'assetqr{}.png'.format(f.id), 'image/png', img_io.len, None)
            # update the object record with the qrcode
            f.qrcode=img_file
            f.save()
        formset.save_m2m()
1

There are 1 answers

0
Rowan Ingram On BEST ANSWER

I have worked around the problem. Instead of editing the asset model directly through save_formset, I have used save_model on the parent, and used that to edit the child. Thus:

def save_model(self, request, obj, form, change):
    # save the object first so we get an id number etc.
    obj.save()
    obj.asset.save()
    # determine the URL
    url='{}{}'.format(HOMEURL,obj.get_absolute_url())
    # build a qr code
    qr = qrcode.QRCode(box_size=3)
    qr.add_data( 'FloWave TT {} {}'.format(obj,url))
    qr.make(fit=True)
    img=qr.make_image()
    # save to memory
    img_io= StringIO.StringIO()
    img.save(img_io,'PNG')
    img_file=InMemoryUploadedFile(img_io, None, 'qr{}.png'.format(obj.id), 'image/png', img_io.len, None)
    # update the object record with the qrcode
    obj.asset.qrcode=img_file
    obj.asset.save()
    obj.save()