自定义django admin ChangeForm模板/添加自定义内容

时间:2016-10-04 06:56:41

标签: python django django-admin

我能够将(跛脚)静态文本插入到更改表单管理页面,但我真的希望它使用当前正在编辑的对象的上下文!

例如,我想在MyObject更改表单上格式化一个URL,以包含来自ForeignKey连接对象(obj)的ID作为链接。

我的管理对象:

class MyObjectChangeForm(forms.ModelForm):
    class Meta:
        model = MyObject
        fields = ('field1', 'obj',)

class MyObjectAdmin(admin.ModelAdmin):
    form = MyObjectChangeForm
    list_display = ('field1', 'obj')
    def render_change_form(self, request, context, *args, **kwargs):
        self.change_form_template = 'admin/my_change_form.html'
        extra = {'lame_static_text': "something static",}
        context.update(extra)
        return super(MyObjectAdmin, self).render_change_form(request,
            context, *args, **kwargs)

我的模板templates/admin/my_change_form.html

{% extends "admin/change_form.html" %}

{% block form_top %}
    {{ lame_static_text }}
    <a href="http://example.com/abc/{{ adminform.data.obj.id }}?"/>View Website</a>
{% endblock %}

{{adminform.data.obj.id}}电话显然不起作用,但我想要沿着这些方向做点什么。

如何将当前对象的动态上下文插入管理员更改表单?

2 个答案:

答案 0 :(得分:7)

change_view

中添加额外的背景信息
class MyObjectAdmin(admin.ModelAdmin):

# A template for a very customized change view:
change_form_template = 'admin/my_change_form.html'

def get_dynamic_info(self):
    # ...
    pass

def change_view(self, request, object_id, form_url='', extra_context=None):
    extra_context = extra_context or {}
    extra_context['osm_data'] = self.get_dynamic_info()
    return super(MyObjectAdmin, self).change_view(
        request, object_id, form_url, extra_context=extra_context,
    )

答案 1 :(得分:2)

我相信您要寻找的魔术变量是“原始”变量,其中包含更改形式正在编辑的python对象:

<a href="http://example.com/abc/{{ original.id }}?"/>View Website</a>