Django内联和list_display_links的替代品

时间:2015-01-21 10:25:33

标签: django django-admin

我的模型包括Person,Contract和Project类。当一个人有一个项目时,就会签订合同。

我还有一个内联版本,以便同时显示一个人的合同。由于 list_display_links 不能与内联一起使用,我使用函数将字段 type_contract 与其合约页面链接,但是当我尝试对字段执行相同操作时项目它也需要我签订合同(我想因为它在合同而不是项目中)。

所以我的问题是:如何将内联中显示的项目与其各自的人员/合同相关联?

models.py

class Person(models.Model):
    name = models.CharField(max_length=32, verbose_name=_(u"Name"))
    surname = models.CharField(max_length=32, verbose_name=_(u"Surname"))
    address = models.CharField(max_length=32, verbose_name=_(u"Address"))

class Contract(models.Model):
    person = models.ForeignKey(Person) #person hired
    project = models.ForeignKey(Project, blank = True, null = True) #related project
    type_contract = models.CharField(max_length = 9, blank = True, choices = TYPO_CONTRACTO, verbose_name = _(u"Type of contract(Full time/grant/Partial time...)"))

    def link_to_contract(self): #Allows me to link to the contract class
        if self.id:
            return "<a href='../../contract/%s' >%s</a>" % (str(self.id), str(self.type_contract))
    else:
        return "Not present"

    link_to_contract.allow_tags = True
    link_to_contract.short_description = "Type contract"

class Project(models.Model):
    name = models.CharField(max_length=32, verbose_name=_(u"Name"))
    principal_researcher = models.ForeignKey(Person, blank = True, verbose_name=_(u"Researcher associated with the project"))

admin.py

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):

    inlines = [
        ContractInline,
    ]

class ContractInline(admin.TabularInline):
    readonly_fields = ["project", "link_to_contract"]
    list_display = ["type_contract", "project"]

    fieldsets = [
        [ None,
            {
                "fields": [
                    ("link_to_contract"),#
                ]
            }
        ],
        [ None,
            {
                "fields": [
                    ("project"),
                ]
            }
        ],

    ]

    model = Contract
    extra = 0

@admin.register(Contract)
class ContractAdmin(admin.ModelAdmin):
list_display_links = ["proyecto", "persona"]
list_display = ["type_contract, "person", "project"]

@admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
    list_display_links = ["principal_researcher", "name"]
    list_display = ["name", "principal_researcher"]

2 个答案:

答案 0 :(得分:0)

继续上述答案:

from django.utils.html import format_html

fields = ('link_to_project', ..)

def link_to_project(self): 
    if self.project.id:
        return format_html("<a href='../../project/%s' >%s</a>" % (str(self.project.id), str(self.project.name))
    else:
        return "Not present"
link_to_project.allow_tags = True

答案 1 :(得分:-1)

 def link_to_project(self): 
    if self.project.id:
        return "<a href='../../project/%s' >%s</a>" % (str(self.project.id), str(self.project.name))
 else:
    return "Not present"