2

Basically, what I want to achieve is to have a media form that show an image thumbnail after I choose the file in the add or edit interface. I try using this code but it returned in this error.

Unknown field(s) (admin_image) specified for ImageMedia. 
Check fields/fieldsets/exclude attributes of class ImageMediaAdmin.

This is the model class:

class ImageMedia(models.Model):
    caption = models.CharField(max_length=64)
    picture = models.ImageField(upload_to='image_media', blank=True)

    def admin_image(self):
        return '<img src="%s" height="300px"/>' % self.picture
    admin_image.allow_tags = True

    def __str__(self):
        return self.caption

This is the admin class

class ImageMediaAdmin(admin.ModelAdmin):
    list_display = ('caption', 'picture', 'admin_image')
    search_fields = ('caption', 'picture')
    fields = ('caption', 'picture', 'admin_image')

admin.site.register(ImageMedia, ImageMediaAdmin)
1
  • You need to remove it from fields, since its not a field but a function; that will get rid of the immediate problem. Oct 6, 2014 at 4:08

1 Answer 1

2

You need to change ImageMediaAdmin to specify admin_image as a readonly_field.

class ImageMediaAdmin(admin.ModelAdmin):
    list_display = ('caption', 'picture', 'admin_image')
    search_fields = ('caption', 'picture')
    fields = ('caption', 'picture', 'admin_image')
    readonly_fields = ['admin_image']
2
  • Its not a field, but a callable. You can't have a callable in the fields tuple. Oct 6, 2014 at 4:09
  • That's what the readonly_fields is there to help with. I've used this before and it's worked.
    – schillingt
    Oct 6, 2014 at 4:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.