Django Admin:如何以内联方式显示在模型上定义的属性? [英] Django Admin: how to display properties defined on model in an inline?
本文介绍了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']}),
]
我已经尝试过一些类似的事情,包括 age(),定义了一个 get_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.
推荐答案
将字段添加到 readonly_fields
元组。
请注意,这仅适用于Django 1.2 +。
Note this only works in Django 1.2+.
这篇关于Django Admin:如何以内联方式显示在模型上定义的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文