向django admin添加自定义按钮或标签

时间:2011-06-14 10:27:07

标签: python django-admin

我想在django管理页面添加一些html元素(按钮,“a”标签等)。我该怎么做?请帮忙。

3 个答案:

答案 0 :(得分:1)

不确定要添加内容的位置,但这是我在其他地方找到的解决方案,以更改FileField的HTML(在我的情况下,我想在ImageField中显示当前图像)。

换句话说,你可以创建一个小部件来修改你想要自定义的字段的html:

# Widget that modifies the output of a FileField
class OutputWidget(AdminFileWidget):
    # Overloaded django magic
    def render(self, name, value, attrs=None):
        output = []
        # This is the place where we edit the output    
        if value and getattr(value, "url", None):
            image_url = value.url
            output.append(u' <a href="%s" target="_blank"><img src="%s" alt="%s" /></a>' % (image_url, image_url, image_url))
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

# ModelAdmin class that is applied to the model
class MyModelSettings(admin.ModelAdmin):
    # Overloaded django magic
    def formfield_for_dbfield(self, db_field, **kwargs):
        # Look for the field we want to edit and register the widget with it
        if db_field.name == 'nameOfFieldIWantToEdit':
            request = kwargs.pop("request", None)
            kwargs['widget'] = OutputWidget
            return db_field.formfield(**kwargs)
        return super(MyModelSettings,self).formfield_for_dbfield(db_field, **kwargs)

# Register my overloaded settings with the model
admin.site.register(MyModel, MyModelSettings)

代码进入admin.py,您可以在其中注册模型。

答案 1 :(得分:0)

答案 2 :(得分:0)

我使用了上面的Omokoli解决方案但是为了让字段使用我做的自定义小部件:

class MyModelAdminForm(forms.ModelForm):
    class Meta:
        model = get_model('myapp', 'mymodel')
        widgets = {
            'original_link': OutputWidget,
        }