简体   繁体   中英

How do I add a custom inline admin widget in Django?

This is easy for non-inlines. Just override the following in the your admin.py AdminOptions:

def formfield_for_dbfield(self, db_field, **kwargs):
    if db_field.name == 'photo':
        kwargs['widget'] = AdminImageWidget()
        return db_field.formfield(**kwargs)
    return super(NewsOptions,self).formfield_for_dbfield(db_field,**kwargs)

I can't work out how to adapt this to work for inlines.

It works exactly the same way. The TabularInline and StackedInline classes also have a formfield_for_dbfield method, and you override it the same way in your subclass.

Since Django 1.1, formfield_overrides is also working

formfield_overrides = {
    models.ImageField: {'widget': AdminImageWidget},
}

Working example:

class PictureInline(admin.StackedInline):
    model = Picture_Gallery
    extra = 3
    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'name':
            kwargs['widget'] = MyWidget()
        return super(PictureInline,self).formfield_for_dbfield(db_field,**kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM