python - 如何在 Django ModelAdmin 字段集中调用模型方法?

标签 python django django-models django-admin

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

模型.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

管理员.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.

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

最佳答案

像那样(从内存中):

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'

关于python - 如何在 Django ModelAdmin 字段集中调用模型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14777989/

相关文章:

python - 为什么该图的底部有额外的空间?

python - 使用 Opencv SIFT 时 matches1to2 出错

python - Django django.db.utils.ProgrammingError。关系 <<Pages_account>> 不存在

python - 如何在 django View 中显示带有超链接的树结构

django - 如何在使用 UserRegisterForm 时停止 django 自动激活用户

python - 完全丢失: Python configure script runs with errors

python - 从 python 中杀死一个子进程,包括它的子进程

django和South移民冲突(0007_two ...和0007_one)如何解决?

python - Django - 是否可以迭代方法?

python - Django 自定义用户模型和用户管理器