如何在django ModelAdmin字段集中调用模型方法?

时间:2013-02-08 17:23:39

标签: python django django-models django-admin

我想在数据库中已存在数据时在管理表单上显示嵌入式地图。我有以下代码:

models.py

class Address(models.Model):
    address = models.CharField()

    def address_2_html(self):
        if self.address:
            # Return html for an embedded map using the entered address.
            return embedded_map_html
        else:
            return ''
    address_2_html.allow_tags = True

admin.py

class AddressAdmin(admin.ModelAdmin):
    fieldsets = [(label, {'fields': ['address','address_2_html']}),]

这不起作用。我收到一个错误:

'AddressAdmin.fieldsets[1][1]['fields']' refers to field 'address_2_html' that is missing from the form.

我尝试的另一件事是使用'fieldsets'的'description'选项,但是,在AddressAdmin的范围内无法访问'address_2_html'。我确实成功地使用“描述”嵌入了静态地图,这很酷但不够酷。

2 个答案:

答案 0 :(得分:22)

就像那样(来自记忆):

class AddressAdmin(admin.ModelAdmin):
    fieldsets = [(label, {'fields': ['address','address_2_html']}),]
    readonly_fields = ['address_2_html']

    def address_2_html(self, obj):
        return obj.address_2_html()
    address_2_html.allow_tags = True
    address_2_html.short_description = 'Address display'

答案 1 :(得分:2)

通过覆盖get_fieldsets()解决了问题,因为get_fieldsets()方法允许访问模型对象Address。

def get_fieldsets(self, request, obj=None):
    fs = [
        (self.label,  {'fields': ['address',]}),
        ('Map', {'fields': [], # required by django admin
                'description':obj.address_2_html(),
         }),
    ]
    return fs