我有一个名为Event
的django模型,与Relationship
具有通用内联关系,如下所示:
# models.py
class Person(models.Model):
...
class Role(models.Model):
...
class Event(models.Model):
...
class Relationship(models.Model):
person = models.ForeignKey(Person)
role = models.ForeignKey(Role)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey("content_type", "object_id")
# admin.py
class RelationshipInline(generic.GenericTabularInline):
model = Relationship
extra = 0
class EventAdmin(admin.ModelAdmin):
inlines = [RelationshipInline]
我想找到一种方法来编辑内联,不仅来自活动管理页面,还来自人员管理页面。到目前为止,我已添加以下代码以在人员页面中显示内联
class ReverseRelationshipInline(admin.TabularInline):
model = Relationship
class IndividualAdmin(admin.ModelAdmin):
inlines = [ReverseRelationshipInline]
但是我在表单中得到content_type
和object_id
字段,对于管理员用户来说它不是很有用,因为它只是对主键的引用。我更愿意解析并显示content_object
(即使它不可编辑,也可以在列表中了解与人有关的对象)。
建议的任何方向?
感谢。
答案 0 :(得分:1)
您的“ReverseRelationshipInline”必须是GenericTabularInline,而不是TabularInline。这就是全部: - )
<强>更新强>
我想我现在明白你所追求的是什么,我的回答是:
您将无法编辑内联对象的内容对象,但您想要很好地展示它,甚至可以作为其更改表单的链接。
向Relationship添加一个返回这样一个HTML链接的函数,为你的内联提供你自己的ModelForm并指定你想要的字段,现在包括你的新函数值(只读)。像这样(未经测试):
# models.py
from django.core import urlresolvers
class Relationship(models.Model):
...
def link_content_object_changeform(self):
obj = self.content_object
change_url = urlresolvers.reverse(
'admin:%s_%s_change' % (
obj._meta.app_label,
obj._meta.object_name.lower()
),
args=(obj.id,)
)
return u'<a href="%s">%s</a>' % (change_url, obj.__unicode__())
link_content_object_changeform.allow_tags = True
link_content_object_changeform.short_description = 'in relation to'
# admin.py
class ReverseRelationshipInlineForm(forms.ModelForm):
class Meta:
model = Relationship
fields = ('person', 'role', 'link_content_object_changeform')
readonly_fields = ('link_content_object_changeform',)
class ReverseRelationshipInline(admin.TabularInline):
model = Relationship
form = ReverseRelationshipInlineForm