[Fixed]-In django admin how do you access a function in a child model?

1👍

The images field on your BlogWidgetCarousel is a ManyToManyField, which returns a queryset of Image objects.

So, first, you need to see if you have any image instances to display, and then grab the first one, or whichever you want to use:

class Image(models.Model):
    . . .

    def thumb(self):
        return '<a href="{0}"><img src="{0}"></a>'.format(self.image.url)


class BlogWidgetCarouselInline(admin.TabularInline):
 . . .

    def thumb(self):
        images = self.images.all()
        if images:
            return images[0].thumb()
        return ''

In this example, an empty string is returned, but you could just as easily return a “default” thumbnail path. I’m not a big fan of rendering HTML in the Python code, so personally I would move that portion to a template fragment:

from django.template.defaultfilters import mark_safe
from django.template.loader import render_to_string


class Image(models.Model)
    . . .

    def thumb(self):
        return mark_safe(render_to_string('_thumb.html', {'image': images[0].image}))


# _thumb.html

<a href="{{ image.url }}"><img src="{{ image.url }}"></a>

Leave a comment