Django Admin:如何在内联中显示模型上定义的属性? [英] Django Admin: how to display properties defined on model in an inline?

查看:20
本文介绍了Django Admin:如何在内联中显示模型上定义的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

This is a follow-up to this question. How do I display properties defined on a child model in an inline on the parent? To illustrate, I have this model:

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

Question is: how do I show 'age' in an inline on User? This is what I have:

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

I've tried a few things like this, including 'age()', defining a 'get_age' getter for the Inline, etc. They result in some version of this error:

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

解决方案

Add the field to both the readonly_fields tuple and fieldsets field as well.

Note this only works in Django 1.2+.

这篇关于Django Admin:如何在内联中显示模型上定义的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆