O
O
ooker2020-10-26 16:13:41
Django
ooker, 2020-10-26 16:13:41

Battery for image view in Django admin panel?

Good afternoon!
I use this construction
admin.py

class BlogPromoHeaderAdmin(admin.ModelAdmin):
    list_display = ("id", "promoheader", "get_image")

    def get_image(self, obj):
        return mark_safe(f'<img src={obj.promoheader.url} width="100"')

    get_image.short_description = "Изображение"

The code works but with errors.
When deleting a photo in an already created article, an error appears.
This method does not work on hosting.
Is there a normal battery for viewing pictures in the admin panel, who met?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Fr, 2020-10-27
@ooker

The error is due to the fact that you are accessing a non-existent field after deletion.
The simplest solution is to move the get_image function to the model and implement it like this

def get_image(self):
  try:
     return mark_safe(f'<img src={self.promoheader.url} width="100"')
  except:
    return ""
get_image.short_description = "Изображение"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question