【问题标题】:Django Admin: how to display properties defined on model in an inline?Django Admin:如何在内联中显示模型上定义的属性?
【发布时间】:2011-03-27 09:15:58
【问题描述】:

这是question 的后续行动。如何在父模型的内联中显示在子模型上定义的属性?为了说明,我有这个模型:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True, primary_key=True, related_name='profile')
    ...
    @property
    def age(self):
        if self.birthday is None:
            return None

        td = datetime.date.today() - self.birthday
        return td.days / 365

问题是:如何在用户的内联中显示“年龄”?这就是我所拥有的:

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    fk_name = 'user'
    max_num = 1
    fieldsets = [
        ('Demographics', {'fields': ['birthday', 'age']}),
    ]

我已经尝试了一些类似的方法,包括“age()”、为内联定义一个“get_age”getter 等。它们会导致此错误的某些版本:

ImproperlyConfigured: 'UserProfileInline.fieldsets[1][1]['fields']' refers to field 'age' that is missing from the form.

【问题讨论】:

    标签: django django-models django-admin


    【解决方案1】:

    将该字段同时添加到 readonly_fields 元组和 fieldsets 字段中。

    请注意,这只适用于 Django 1.2+。

    【讨论】:

    • 当我将 readonly_fields = ['age',] 添加到 UserProfileInline 类中时,如上所示,我没有收到错误消息,但它在管理员中没有显示任何内容。我错过了什么吗?我正在使用 Django 1.2,但仍在学习我的方式 - 感谢您的帮助。
    • 这很奇怪 - 它应该可以工作。你确定服务器已经重启了吗?
    • 我已经在 Django 1.6 中成功使用了这个。
    • 注意:这是一个只读的解决方案——如果你有一个可设置的属性,你可以做一些事情,比如定义一个表单并覆盖保存方法。
    • 您需要将其添加到 readonly_fields 和 fieldset 中。一开始我以为它行不通,但后来我尝试了这个。
    猜你喜欢
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 2011-02-23
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 2021-06-18
    相关资源
    最近更新 更多