views:

201

answers:

3

I've defined a model which contains a link an image. Is there a way to display the image in the model items list? My model looks like this:

class Article(models.Model):
    url = models.CharField(max_length = 200, unique = True)
    title = models.CharField(max_length = 500)
    img = models.CharField(max_length = 100) # Contains path to image

    def __unicode__(self):
       return u"%s" %title

Is there a way to display the image together with title?

A: 

You can overwrite django admin view for your model. See http://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-admin-templates for more details.

In a brief you need to create a template: templates/admin/your_app/article/change_form.html And there add html to display the image.

Piotr Czapla
A: 

http://www.djangosnippets.org/snippets/239/

there that, plus, if you're using 1.2 you can combine the above with read-only fields.

nbv4
+4  A: 

You can create a model instance method with another name, allows HTML tags for its output and add this method as a list field. Here is an example:

First add a new method returning the HTML for the image inclusion:

class Article(models.Model):
    ...
    def admin_image(self):
        return '<img src="%s"/>' % self.img
    admin_image.allow_tags = True

Then add this method to the list:

class ArticleAdmin(admin.ModelAdmin):    
    ...
    list_display = ('url', 'title', 'admin_img')
Michael
Got a problem. Could you take a look plsTypeError at /admin/'MediaDefiningClass' object is not iterableRequest Method: GETRequest URL: http://127.0.0.1:8000/admin/Exception Type: TypeErrorException Value: 'MediaDefiningClass' object is not iterable
Oleg Tarasenko
Actually fixed the previous one, now have this:'admin_img' is not a callable or an attribute of ....
Oleg Tarasenko
ok, please ignore... was a typo
Oleg Tarasenko