django - 永远不会调用 Django 管理界面中字段的只读方法

标签 django django-admin

Django 文档 state您可以在管理界面中为只读字段输出自定义 HTML。这正是我需要的,但它似乎不起作用。

在 admin.py 中:

from django.contrib import admin

class ExampleAdmin(admin.ModelAdmin):
    readonly_fields = ('myfield', )

    def myfield(self, instance):
        print 'This part of the code is never reached!'
        return u'<b>My custom html for the readonly field!</b>'

    myfield.allow_tags = True

admin.site.register(State, StateAdmin)

在models.py中:
class State(models.Model):
    myfield = MyCustomField()
    ... etc ...

class MyCustomField(models.TextField):
    def to_python(self, value):
        ... etc ...

该字段在管理编辑页面上显示为只读。但是,永远不会调用应该创建自定义 html 的 'myfield' 方法。

有谁知道我做错了什么?

亲切的问候,

帕特里克

最佳答案

查看“django/contrib/admin/util.py”文件的lookup_field方法,这似乎是预期的行为。这是您正在使用的代码:

readonly_fields = ('myfield', )

myfield是在您的模型中定义的实际字段,将其放在 readonly_fields 中只会使它不可编辑;它不允许您自定义向用户显示的内容。为了做到这一点,你必须给 readonly_fields一些不是实际字段的东西,例如 myfield_readonly .然后您必须重命名您的 ModelAdminmyfield方法 myfield_readonly当然,还有myfield.allow_tags = True .您可能还想添加 myfield_readonly.short_description = 'My Field' .最后,您要离开实际的 myfield使用 exclude 退出表单或 fields .

关于django - 永远不会调用 Django 管理界面中字段的只读方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14915549/

相关文章:

json - 通过 AJAX 将 JSON 对象从 Django View 返回给客户端

python - 与 Django 的多个并发数据库事务?

python - 如何反序列化 GeoServer WFS GeoJSON?

python - Django模板不能循环defaultdict

python - 我应该如何在 django admin 中表示一个 bit flags int 字段?

Django 管理员 : Setting list_display conditionally

python - 使用 django-piston 时出现 400 Bad Request 错误

python - 为 CustomUser 指定的未知字段(密码 1、密码 2)

javascript - 注销后禁用浏览器 'Back' 按钮?

Django模型外键的内联动态默认值