Wednesday, April 25, 2012

Re: Overriding an admin widget?

Oh, I see what's going on.  I marked the field as readonly.  Apparently the widget only gets created if the field is editable (I guess that makes sense).



On Apr 25, 2012, at 1:28 PM, Roy Smith wrote:

Ooops, forgot to mention, I'm using django 1.4.


On Apr 25, 2012, at 12:51 PM, Roy Smith wrote:

I'm trying to get the admin to give me a thumbnail for an ImageForm.  Following the suggestion at http://djangosnippets.org/snippets/1580/, I've got the following code:

from django import forms
from django.contrib import admin
from django.db import models
from django.utils.safestring import mark_safe

class AdminImageWidget(forms.FileInput):
    def __init__(self, attrs={}):
        assert 0
        super(AdminImageWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        output = []
        if value and hasattr(value, "url"):
            output.append(('<a target="_blank" href="%s">'
                           '<img src="%s" style="height: 28px;" /></a> '
                           % (value.url, value.url)))
        output.append(super(AdminImageWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

class ImageVersionAdmin(admin.ModelAdmin):
    readonly_fields = ('image',
                       'data')
    formfield_overrides = {
        models.ImageField: {'widget': AdminImageWidget,
                            'label': 'My Label',},
        }

admin.site.register(ImageVersion, ImageVersionAdmin)

The problem is, I'm still getting the standard admin display.  I stuck the "assert 0" in AdminImageWidget.__init__() just to prove that it's never being called.  What magic am I missing?

My model looks like:

class ImageVersion(Model):
    image = ForeignKey(Image)
    data = ImageField(upload_to="images/foo")

---
Roy Smith





---
Roy Smith





---
Roy Smith



No comments:

Post a Comment