Disable image-cleanup in Django

I create a few badge for users. I using django-CleanUp for delete other media objects. When user’s score high enough I want change old badge to new badge. But when change images, old image(badge) is deleted. I dont want this. I want keep old badge because is still used other users

My Views:

def liked_post(request, pk):
    user_update = get_object_or_404(UserRanks, user = post.username)
        
    if  user_update.score < 50:
          user_update.rank_image = "guard.gif"

    elif user_update.score < 100:
           user_update.rank_image = "captain1.gif"

    elif user_update.score < 300:
           user_update.rank_image = "knight1.gif"
    user_update.save()

my Models:

class UserRanks(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
   rank_image = models.ImageField(
        verbose_name="Rank Gif", default="guard.gif", null=True, blank=True)
   score = models.IntegerField(
        null=True, blank=True, verbose_name="Score", default=0)

   def save(self, *args, **kwargs):
       super(UserRanks, self).save(*args, **kwargs)

is there a way to do keep old image without remove the django-clean-up?

Answer

You don’t have to create a separate media item for the same badge for each user. Keep the badge images in static storage (not media) and simply have a model method that returns the correct image URL:

from django.templatetags.static import static

class UserRanks(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    score = models.IntegerField(
                null=True, blank=True, verbose_name="Score", default=0)
    # Delete "rank_image" column

    @property
    def rank_image_url(self):
        if self.score < 50:
            return static("image/guard.gif")
        elif user_update.score < 100:
            return static("image/captain1.gif")
        elif user_update.score < 300:
            return static("image/knight1.gif")

Also remove the code that updates rank_image from your view. Then simply use something like

<img src="{{ user.userranks.rank_image_url }}" />

in your templates.