Django admin file upload with current model id

前端 未结 5 1046
轮回少年
轮回少年 2020-12-01 03:29

I\'m trying to create a simple photo gallery with the default Django admin. I\'d like to save a sample photo for each gallery, but I don\'t want to keep the filname. Instead

5条回答
  •  悲哀的现实
    2020-12-01 03:37

    For Django 2.2, follow the below code.

    def save(self, *args, **kwargs):
        if self.pk is None:
            saved_image = self.image
            self.image = None
            super(Gallery, self).save(*args, **kwargs)
            self.image = saved_image
            if 'force_insert' in kwargs:
                kwargs.pop('force_insert')
    
        super(Gallery, self).save(*args, **kwargs)
    

    Add the above code snippet to your 'class Gallery'.

    P.S.: This will work for DRF as well when you save via views.py. Note that second if (condition) is required for DRF.

提交回复
热议问题