Radek
Radek

Reputation: 1189

How to change True value into green check in the Django admin ListView

models.py

class Example(models.Model):
    sort = models.PositiveIntegerField(default=0, blank=False, null=False)
    created = models.DateTimeField(editable=False)
    modified = models.DateTimeField(editable=False)
    online = models.BooleanField(default=True)
    title = models.CharField(max_length=300, blank=True)
    slug = models.SlugField(max_length=255, blank=True, unique=True)
    main_image = models.ImageField(upload_to='images', blank=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        if not self.id:
            self.created = timezone.now()
        self.modified = timezone.now()
        super().save(*args, **kwargs)

    def image_tag(self):
        if self.main_image:
            return True
        else:
            return False

Image Tag

As you can see if you have BooleanField online - it will change the True or False to Green or Red. How can I achieve - that when my ImageField is empty it would do the same. I have created an image_tag method that would return True or False but not sure what to do next - do I need to override the template - is there a way to do it without?

Upvotes: 3

Views: 1256

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

The correct way is to set a boolean attribute on the method itself. You should also make sure the method always returns a bool.

def image_tag(self):
    return bool(self.main_image)
image_tag.boolean = True

(This is documented, but there's no way to link to the exact place: see about halfway through the list_display section.)

Upvotes: 5

Related Questions